# Question
Title: 3D/perspective Top down shooter bullet issues
I'm developing a top-down shooter with multiple levels (ground for ground units, middle level for buildings, top level for air unity).

The problem is the collision. Though I can make the collider box of a bullet be long enough to reach the ground (and collide with it), the real issue is optical.

When the bullet is fired from a aircraft and collides with some object on the ground (building, ground unit) it will be optically offset due to the perspective camera, because it looks like the shot "by-passed" the target as seen below

Is there any way to make the bullets collide perspectively correct? I'm using Unity3d Engine and it offers only simple colliders (box, sphere, cylinder, mesh and wheel), though I don't think a cone-formed collider would solve this issue.

I'd need a (cheap) way to check if it's overlapping a destructible object? I thought of casting a ray from the camera through the bullet and if it hits something destructible, trigger an action, but that's quite punctual and maybe to performance heavy on certain number of bullets

# Answer
> 2 votes
I've solved it by putting the projectile collider in a child object and rotate it towards the camera.

### Update

It was as simple as dropping this script into the collider for the projectiles. One makes them very long, so they can touch the ground objects.

```
public class AlignWithCamera : MonoBehaviour {
    private Transform myTransform;
    private Transform cameraTransform;

    public void Update () {
        Align();
    }

    public void OnEnable() {
        Initialize();
        Align();
    }
    public void Initialize() {
        myTransform = transform;
        cameraTransform = Camera.main.transform;
    }

    public void Align() {
        Vector3 direction = cameraTransform.position - myTransform.position;
        myTransform.rotation = Quaternion.FromToRotation(Vector3.up, direction);
    }
}

```

Some of this isn't necessary anymore, since Unity3D has been optimized a lot in the past 6 years. The myTransform was basically an optimization to avoid calling `transform` property on every update, but it should be a non-issue by now.

And the reason I did initialize in `OnEnable` is cause my projectiles were recycled in an object pool, so they are only created once and then put inactive one used or go out of screen and return back to the pool.

---
Tags: c#, 3d, bullet-physics, perspective
---


# Question
Title: How can I make a rectangle to an irregular shape?
I used masking for breaking an image into the below pattern. Now that it's broken into different pieces I need to make a rectangle of each piece. I need to drag the broken pieces and adjust to the correct position so I can reconstruct the image. To drag and put at the right position I need to make the pieces rectangles but I am not getting the idea of how to make rectangles out of these irregular shapes. How can I make rectangles for manipulating these pieces?

This is a follow up to my previous question.

# Answer
> 3 votes
Since you're using static patterns for breaking the image up, you can use static defined rectangles too. Simply pre-define the bounds for each rectangle by manually checking the placement for each. As shown in the image I gave you before, the rectangles should just be the minimum size required to enclose each shape.

# Answer
> 1 votes
I also recommend using predefined rectangles as byte56 recommended; but if you insist to dynamically create those rectangles, you can easily check what are the most left, most right, most up and most bottom pixel in your pattern. their coordinates will define edges of your rectangle.

---
Tags: iphone, cocos2d-iphone, objective-c
---


# Question
Title: Is it possible to procedurally place objects in a non-gridded game?
I'd like to implement procedural world generation, but I don't want it to look gridded or blocky, where everything is obviously placed on an integer grid.

I know that you can do this in gridded worlds by inputting a square's x and y into a noise function, or similar, but is it possible to generate a more natural looking object placement using procedural methods?

This is in the context of an adventure game, if it matters.

**Edit:** I guess I should have been a bit more clear in my original question, but I'm mostly wondering about the actual placement of objects in game, e.g. trees, buildings.

**Edit 2:** I feel silly now. I typed up this question too quickly, and I didn't realize I was asking a yes or no question. I've reposted my actual question which asks, more specifically, how this can be done. Sorry!

# Answer
**EDIT**

To address you change from generation of worlds to generation of objects in game.

Yes, the same still applies. For example, included in my original post, SpeedTree is used for placing vegetation in game:

So yes, it's entirely possible. Most any large world (Skyrim for example) will use some form of procedural generation for placing items like this. They're not all placed by hand and they're clearly not aligned to a grid.

---

Procedural generation absolutely has use outside of a grid world. You need look no further than Terragen for excellent examples of such:

SpeedTree is another popular choice for many games for producing vegetation.

Noise generation commonly fractal in nature, that means you can continue "down" to smaller and smaller details.

And a popular method from Red Blob Games uses polygons, blending and noise:
> 6 votes

---
Tags: mathematics, maps, procedural-generation
---


title: Distance between two 3D objects' faces

text:
# Question
Title: Distance between two 3D objects' faces
I'm really newbie on programming and I'm making some tests. I couldn't find nowhere on Internet how could I calculate the distance between two 3D objects' faces. Is there anyway?

Detailing, as an example, I have two 3D cubes. Each one has a vector3 position designating it's center on the 3D space and an orientation matrix. And each cube has a size (float width, float height and float length).

I could get a simple distance between them by calling Vector3.Distance(), but it doesn't consider its sizes, just the position. Then the distance would be between its centers.

Is there any way to calculate the distance between the faces? Thanks for any reply.

# Answer
There are a variety of approaches you could take for this, depending on how fast and how accurate you need it to be, and how much time you're willing to spend on it.

If a very approximate answer will suffice, you could store a "radius" for each object and calculate the distance between two objects as the distance between their centers, minus both of their radius values.

A somewhat more accurate way would be to apply a separating axis test. You could use the vector between the centers as a trial axis for a faster version of this algorithm, or go all the way and try all the possible axes called for by the theorem, taking the minimum separation across all the trial axes.

A very accurate and fast way would be to use the GJK algorithm, but it is complicated and difficult to implement (though you can probably find some code for it around the Web).
> 3 votes

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


# Question
Title: How can you procedurally place objects in a non-gridded game?
*This is a follow-up question to this question. I mistakenly worded the question, but got a good answer before I could correct myself, so I didn't want to delete it. Sorry!*

---

Now that I know that it *is* possible, I'd like to implement procedural world generation, but I don't want it to look gridded or blocky, where everything is obviously placed on an integer grid.

I know that you can do this in gridded worlds by inputting a square's x and y into a noise function, or similar, but how can I generate a more natural looking object placement using procedural methods?

This is in the context of an adventure game, if it matters.

# Answer
**Noise-based Density Field**

I'd start generating a "density-field", which would be a collection of points and the probability of your object occuring there. You can use a noise function such as Perlin noise to generate a "strength-field", which you can then modify using your own known parameters (elevation, normal direction, etc.)

Then for each cell in your density field, you can check if the value is high enough to place an object. You then place an object *at a random point in that cell* instead of at the exact center of that cell. You may have to do a cleanup pass to eliminate overlaps where two adjacent cells generate their objects directly next to the edge.

**Cellular Rules**

For many natural objects, there are certain rules that govern their occurrence. In the case of rocks, you could use a ruleset such as "pebbles get initially created in dried-out streams and rivers. Large rounded rock formations occur in areas where the soil gets worn down by erosion. large-scale stripes of rocks form from retreating glaciers." In the case of trees and bushes, they obey certain rulesets like "Trees will not grow within 3 feet of each other; bushes do not grow as well under trees; Old, aging forests have rich soil that promotes thick undergrowth". If you start with the randomized cell values from step 1 and iterate over a hundred generations of these rules, you will wind up with a more "natural distribution".
> 5 votes

---
Tags: procedural-generation
---


# Question
Title: Using Lerp to create a hovering effect for a GameObject
I want to have a GameObject that has a "hovering" effect when the mouse is over it.

What I'm having trouble with is actually having a color that gradually goes from one color to the next. I'm assuming `Color.Lerp()` is the best function for that, but I can't seem to get it working properly.

Here's my `CubeBehavior.cs`'s `Update()` function:

```
private bool ReachedTop = false;
private float t = 0f;
private float final_t;
private bool MouseOver = false;

// Update is called once per frame
void Update () {
    if (MouseOver) {
        t = Time.time % 1f; // using Time.time to get a value between 0 and 1
        if (t >= 1f || t <= 0f) // If it reaches either 0 or 1...
            ReachedTop = ReachedTop ? false : true;

        if (ReachedTop) final_t = 1f - t; // Make it count backwards
        else final_t = t;

        print (final_t); // for debugging purposes
        renderer.material.color = Color.Lerp(Color.red, Color.green, final_t);
    }
}

void OnMouseEnter() {
    MouseOver = true;
}

void OnMouseExit() {
    renderer.material.color = Color.white;
    MouseOver = false;
}

```

Now, I've tried several approaches to making it reach 1 then count backwards till 0 including a multiplier that alternates between 1 and -1, but I just can't seem to get that effect. The value goes to 1 then resets at 0.

Any ideas on how to do this?

# Answer
Found the solution... Just used my own float instead of using `Time.time`.

```
private bool CountBack = false;
private float Speed = 0.01f;
private float t = 0f;
private float final_t;
private bool MouseOver = false;

// Update is called once per frame
void Update () {
    if (MouseOver) {
        if (!CountBack) {
            t += Speed;
            if (t >= 1f) CountBack = true;
        }
        else {
            t -= Speed;
            if (t <= Speed) CountBack = false;
        }
        final_t = t;
        print (CountBack + "("+final_t+")");
        renderer.material.color = Color.Lerp(Color.red, Color.green, final_t);
    }
}

```
> 3 votes

# Answer
I don't think `if (t >= 1f || t <= 0f)` is ever executed, have you tried stepping through it with a debugger?

For sure `t >= 1f` is never going to be true, because of how % works. `t <= 0f` is going to be true in extremely rare situations, it's definetly never going below 0 and i daubt it'll ever reach zero simply because you're dealing with finite precision.

If i was to suggest something, try using 0.9 instead of 1 and 0.1 instead of 0 or something, i've no idea how precise the timer you're using is. The rest of the logic should work fine.

**EDIT:** The author answered his own question, still i'm leaving a different solution to this in C++.

```
#include <iostream>

int main () {

    float i = 0.f, final_i;
    bool swap = false;

    for(unsigned int k = 0; k < 30; ++k){

        i += 0.1f;

        if ( i >= 1.f ) {
            i = 0.f;
            swap = swap ? false : true;
        }

        if ( swap ) {
            final_i = 1.f - i;
        }
        else{
            final_i = i;
        }

        std::cout<<final_i<<std::endl;
    }

    system("pause");

    return 0;
}

```
> 3 votes

# Answer
Alternately:

```
t = Time.time % 2f;
if (t > 1f)
    t = 2f - t;

```

This will also give you a 't' value which smoothly loops back and forth along the interval \[0..1..0\].
> 2 votes

# Answer
iTween has a ColorTo method that might work as well..

http://itween.pixelplacement.com/documentation.php
> 0 votes

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


title: Game Institute Math Courses

text:
# Question
Title: Game Institute Math Courses
I'm 21 years old and I suck at math, I mean really bad. I don't have the necessary logic to apply it towards programming. I would like to learn the math and logic of applying it. I found Game Institute (http://www.gameinstitute.com) awhile back and heard a lot of praise about them. Are there Math courses any good?

Thank you.

**Edit:** My high school was terrible and did not prepare me for any math. I am fairly decent at programming, I just don't have the logic to apply any mathematics to programming, as an example I don't understand the algorithm of finding the size of a user's screen.

Yes I have heard of KhanAcademy (http://www.khanacademy.org/) and I have completed a lot of maths on his website but I still don't have the logic to apply any of it to programming.

# Answer
> 4 votes
If you suck at maths you don't want to be starting at the game development level because game maths generally uses some advanced concepts, e.g. matrices and some calculus. Other things like vectors, trigonometry (or anything to do with angles) aren't so complex but they aren't beginner-level either.

### Try Khan Academy.

Learn the basics first, then worry about learning stuff specific to game development.

Their courses cover most of the American high school curriculum, and there is a significant amount of maths education available on the site. They're also free-as-in-Wikipedia because the guy who runs the site can afford to do that.

Once you've learned the basics you can also learn stuff specific to game development from Khan Academy, because they teach Linear Algebra and Geometry and other game development topics too.

So: **No. Don't use Game Institute.** First because you suck at maths, second because even if you didn't you can learn the maths for free.

# Answer
> 2 votes
I have access to Game Institute and I do think all of the courses I've done are really good, including the math course. *However*, if you really want to start from the very basics, I would recommend that you watch the videos from **Khan Academy** instead. Some points of interest:

* It's completely *free*!
* Sal who founded the site, is a great teacher, and his videos are both informative and fun.
* The videos start from the *very* basics such as basic addition all the way up to calculus and differential equations. So you can jump in no matter what level you are.
* There are exercises for you to practice what you learn, and a road map that tells you what you should study next (check image below).
* As a bonus, it also covers *many* other subjects besides maths if you're interested.

After you have at least the high school basics down, the Game Institute course will probably make a lot more sense that it would right now. It will probably still be useful because it's very game oriented, dealing with subjects such as vectors, matrix and quaternions, in the context of game development. Still, the Khan Academy will probably be enough since it's quite complete, and actually covers a lot more than the Game Institute course.

# Answer
> 0 votes
Math is hard enough to learn in 4 years with a teacher guiding you. I honestly don't see how you can learn it on your own by following web tutorials. My suggestion is enroll in math course at college or university.

---
Tags: mathematics, physics, trigonometry
---


title: 2D Tile-Based Concept Art App

text:
# Question
Title: 2D Tile-Based Concept Art App
I'm making a bunch of 2D games (now and in the near future) that use a 2D, RPG-like interface. I would like to be able to quickly paint tiles down and drop character sprites to create concept art.

Sure, I could do it in GIMP or Photoshop. But that would require manually adding each tile, layering on more tiles, cutting and pasting particular character sprites, etc. and I really don't need that level of granularity; I need a quick and fast way to churn out concept art.

Is there a tool that I can use for this? Perhaps some sort of 2D tile editor which lets me draw sprites and tiles given that I can provide the graphics files.

# Answer
> 8 votes
Have you seen Tiled? I've used it for this very purpose myself a number of times.

From the website:

> * General purpose tile map editor with XML-based map format
> * Supports orthogonal and isometric maps
> * Custom objects can be placed with pixel precision
> * Full undo/redo and copy/paste support
> * Add custom properties to tiles, layers, objects or the map
> * Automatically reloads tilesets when changed externally
> * Resize or offset your tile map later as needed
> * Efficient tile editing tools like stamp and fill brushes
> * Supports input/output plugins to open and save files in custom formats

This program is a fantastic tool for laying out tile-based maps very quickly, with lots of flexibility. When finished, it can even render your map to an image file.

There's also Mappy. Though I have no real experience with this tool, it does appear to have similar features.

# Answer
> 2 votes
I have used Ogmo Editor for this purpose. It's similar to `Tiled`, but it's simpler hence it has less features.

I was very satisfied with it, but now the version 2 has been released and I haven't tried it yet. Here's a video tutorila for the older version.

---
Tags: art
---


title: Keeping the CCSprite on the screen

text:
# Question
Title: Keeping the CCSprite on the screen
In my cocos2d app I have a CCSprite moving on the screen but it moves off the screen. How can I prevent the CCSprite from moving off the screen?

Thanks

# Answer
You have to make sure your sprite-rectangle is always within the screen bounds. You can ensure this by clamping the x, and y position of the sprite within the screen bounds.

Something like this (this is assuming the anchor point of the sprite is at its center, which is the default):

```
// move sprite using accelerometer

// get screen size
CGSize screen = [[CCDirector sharedDirector] winSize];

// get sprite size
CGSize size = sprite.contentSize;

// get sprite position
CGPoint pos = sprite.position;

// set new position constrained to screen bounds
sprite.position = ccp(
    clampf(pos.x, size.width * 0.5f, screen.width - size.width * 0.5f),
    clampf(pos.y, size.height * 0.5f, screen.height - size.height * 0.5f)
);

```
> 3 votes

---
Tags: cocos2d-iphone, ios, cocos2d, ccsprite
---


title: Bejewelled Next Best jewel selection

text:
# Question
Title: Bejewelled Next Best jewel selection
Is there a game design technique I can use so that I completely remove 'No more moves left' situations. ie. the game should contain no impossible scenarios.

As far as I've guess It all depends on what jewel and where you give the user after a jewel group of 3 or 4 dissolves.

Is it possible ? `An always infinitely solvable Bejewelled game?`

# Answer
> 1 votes
It's certainly possible to create an endless Bejeweled game. PopCap have done so themselves with the latest Bejeweled 3 (the mode is called "Zen Mode").

First of all, you need to make sure *there's at least one valid move* when you first generate the board.

Whenever a player makes a move, you have to calculate the resulting board and search for valid moves. If there are none to be found, you have to control the gems that will be spawned to restore a valid board. Since (at least) 3 gems will be removed with one move and you'll have to spawn 3 replacement gems, you can ensure that these 3 replacement gems will form another valid move with the current board. Endless mode achieved.

Of course it's not ideal that the new move will appear with new gems, but it's a cheap way to always ensure a playable board. And since creating valid moves actually means to *swap* positions of gems, it won't be long before other moves will become possible.

As already mentioned, bombs and other means to clear large parts of the board will add more variety to the gameplay, but they are not needed to ensure an endless mode.

# Answer
> 4 votes
Yes. This would in fact be possible. This is not a case of the halting problem as the case is defined, not arbitrary. To answer this, two parts must be answered; first if a solution exists can it be found, and second will there always be a valid solution to find.

The first part of is how to find a set of replacement tiles (gems) which would produce a playable board. This can be achieved via brute force methods, just check every possible replacement set until a playable one is encountered (There would be more optimal non-brute force methods as well).

The second part is to determine if there will always be a replacement set which will produce a playable set. Any set of tiles removed in a single move is going to be some superset of sets of three tiles, so if in the minimal case of only three being removed, if a playable set can always be found, then for all possible patterns of removed tiles there will be a playable set, as it will contain all the solutions for each set of three removed tiles which is a subset of the removed tiles.

In the minimal case of clearing only three tiles in a row/column, A replacement set containing two tiles of type A separated by a tile of type B (where type A is the type of a tile above or below the cleared set of three in the case of a column of three, or to the left or right in the case of a row of three). This will yield a move where swapping the center of these three tiles with the appropriate A tile alongside it will produce a set of three. This shows that a set of tiles can always be found which will produce a valid move along the column/row where the original tiles were cleared. Restricting future moves to that column or row would, while being a valid solution for an infinity playable game, would not be very fun. But using all the rules for common bejeweled style games, it’s easy to show that there will always exists a solution which will allow for moves outside of that row/column as well. Assume we drop in three A type tiles, where A is one of the tiles above or below / left or right of the removed set of three. This will produce a “bomb” style tile which will clear an area when removed. If we then drop in another replacement set of tiles which results in a match being made with that bomb an area of tiles will be cleared. This area will contain a number of 3 tile subsets within other rows, which means that that future moves will not necessarily be limited to a single row/column.

# Answer
> 3 votes
You have touched upon the halting problem in computer science.

Given a description of an arbitrary computer program, can we deduce if it will stop at some point or run forever? There is a reason this is called a "problem".

The short answer is: no, you cannot guarantee that a Bejeweled game will never have any illegal moves. Because to guarantee it would take infinite computing time.

---
Tags: game-design, level-design
---


title: Octree subdivision problem

text:
# Question
Title: Octree subdivision problem
Im creating octree manually and want function for effectively divide all nodes and their subnodes - For example - I press button and subnodes divided - press again - all subnodes divided again. Must be like - 1 - 8 - 64. The problem is - i dont understand how organize recursive loops for that.

OctreeNode in my unoptimized implementation contain pointers to subnodes(childs),parent,extra vector(contains dublicates of child),generation info and lots of information for drawing.

```
class gOctreeNode
            {
   //necessary fields
    gOctreeNode* FrontBottomLeftNode;
    gOctreeNode* FrontBottomRightNode;
    gOctreeNode* FrontTopLeftNode;
    gOctreeNode* FrontTopRightNode;
    gOctreeNode* BackBottomLeftNode;
    gOctreeNode* BackBottomRightNode;
    gOctreeNode* BackTopLeftNode;
    gOctreeNode* BackTopRightNode;
    gOctreeNode* mParentNode;
    std::vector<gOctreeNode*> m_ChildsVector;
    UINT mGeneration;
    bool mSplitted;
    bool isSplitted(){return m_Splitted;}

    .... //unnecessary fields
    };

```

DivideNode of Octree class fill these fields, set mSplitted to true, and prepare for correctly drawing. Octree contains basic nodes(m\_nodes). Basic node can be divided, but now I want recursivly divide already divided basic node with 8 subnodes. So I write this function.

```
    void DivideAllChildCells(int ix,int ih,int id)
    {
        std::vector<gOctreeNode*> nlist;
        std::vector<gOctreeNode*> dlist;

        int index = (ix * m_Height * m_Depth) + (ih * m_Depth) + (id * 1);//get index of specified node
        gOctreeNode* baseNode = m_nodes[index].get();

        nlist.push_back(baseNode->FrontTopLeftNode);
        nlist.push_back(baseNode->FrontTopRightNode);
        nlist.push_back(baseNode->FrontBottomLeftNode);
        nlist.push_back(baseNode->FrontBottomRightNode);
        nlist.push_back(baseNode->BackBottomLeftNode);
        nlist.push_back(baseNode->BackBottomRightNode);
        nlist.push_back(baseNode->BackTopLeftNode);
        nlist.push_back(baseNode->BackTopRightNode);

        bool cont = true;
        UINT d = 0;//additional recursive loop param (?)
        UINT g = 0;//additional recursive loop param (?)

        LoopNodes(d,g,nlist,dlist);

        //Divide resulting nodes
        for(UINT i = 0; i < dlist.size(); i++)
        {
            DivideNode(dlist[i]);
        }
    }

```

And now, back to the main question,I present LoopNodes, which must do all work for giving dlist nodes for splitting.

```
    void LoopNodes(UINT& od,UINT& og,std::vector<gOctreeNode*>& nlist,std::vector<gOctreeNode*>& dnodes)
    {
        //od++;//recursion depth
        bool f = false;

        //pass through childs
        for(UINT i = 0; i < 8; i++)
        {
            if(nlist[i]->isSplitted())//if node splitted and have childs
            {
                //pass forward through tree
                for(UINT j = 0; j < 8; j++)
                {
                    nlist[j] = nlist[j]->m_ChildsVector[j];//set pointers to these childs
                }
                LoopNodes(od,og,nlist,dnodes);
            }
            else //if no childs
            {
                //add to split vector
                dnodes.push_back(nlist[i]);
            }
        }
    }

```

This version of loop nodes works correctly for 2(or 1?) generations after - this will not divide neightbours nodes, only some corners. I need correct algorithm. Screenshot

All I need - is correct version of LoopNodes, which can add all nodes for DivideNode.

# Answer
I think you're overcomplicating things. If I understood correctly, you want to find all leaf-nodes within your octree and add these to a list of nodes that should be subdivided.

I have no clue what you need the `d` and `g` parameter for.. something like this should work:

```
void LoopNodes(gOctreeNode* node, std::vector<gOctreeNode*>& dnodes)
{
    // check if it's a leaf-node
    if(node->isSplitted()){
        // not a leaf-node, so check all children
        for(UINT i = 0; i < 8; i++){
            LoopNodes(node->m_ChildsVector[i], dnodes);
        }
    } else {
        dnodes.push_back(node);
    }
}

```

Then start the search by passing in your "main" (outermost) cube as node to the function, like this:

```
LoopNodes(mainNode, dnodes);

```
> 2 votes

---
Tags: c++, octree
---


# Question
Title: Collision detection of player larger than clipping tile
I want to know how to check for collisions efficiently in case where the player's box is larger than a map tile.

On the left is my usual case where I make 8 checks against every surrounding tile, but with the right one it would be much more inefficient.

(picture of two cases: on the left is the simple case, on the right is the one I need help with)

How should I handle the right case?

# Answer
I think you can only optimize your existing method if the player's box doesn't rotate (or rotates only at multiples of 90 degrees). In this case, I would do the following:

Let the corners of the player's box be A, B, C and D, and (Ax, Ay) the coordinates of A, etc. The letters go counter-clockwise, starting from the upper left corner.

**Step 1:** You can easily get the indexes of the tiles which contain each of these corners. Use integer division, and the (fixed) size of your tiles. Let these indexes be (Ai, Aj), (Bi, Bj) etc.

**Step 2:** The following tiles (indexes: (Ri, Rj)) will be completely inside the player's box:

(Ai+1, Aj+1) \<= (Ri, Rj) \<= (Ci-1, Cj-1)

**Step 3:** The following tiles will be partially intersecting with the player's box:

(Ri == Ai) && (Aj \<= Rj \<= Bj)

(Ri == Di) && (Dj \<= Rj \<= Cj)

(Rj == Aj) && (Ai \<= Ri \<= Di)

(Rj == Bj) && (Bi \<= Ri \<= Ci)

Implying that i is the horizontal index.
> 0 votes

---
Tags: collision-detection
---


title: Open GL polygons not displaying

text:
# Question
Title: Open GL polygons not displaying
I have tried to follow nehe's opengl tutorial lesson 2. I use sfml for my window creation. The problem I have is that both the triangle and the quad don't show up on the screen:

```
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <iostream>

void processEvents(sf::Window *app);
void processInput(sf::Window *app, const sf::Input &input);

void renderCube(sf::Window *app, sf::Clock *clock);
void renderGlScene(sf::Window *app);

void init();

int main()  {
    sf::Window app(sf::VideoMode(800, 600, 32), "Nehe Lesson 2");

    app.UseVerticalSync(false);

    init();

    while (app.IsOpened())  {
        processEvents(&app);

        renderGlScene(&app);

        app.Display();
    }

    return EXIT_SUCCESS;
}

void init()  {
    glClearDepth(1.f);
    glClearColor(0.f, 0.f, 0.f, 0.f);

    // Enable z-buffer and read and write
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);

    // Setup a perpective projection
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluPerspective(45.f, 1.f, 1.f, 500.f);

    glShadeModel(GL_SMOOTH);
}

void processEvents(sf::Window *app)  {
    sf::Event event;

    while (app->GetEvent(event))  {
        if (event.Type == sf::Event::Closed)  {
            app->Close();
        }

        if (event.Type == sf::Event::KeyPressed &&
            event.Key.Code == sf::Key::Escape)  {
            app->Close();
        }
    }
}

void renderGlScene(sf::Window *app)  {
    app->SetActive();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  // Clear the screen and the depth buffer
    glLoadIdentity();                   // Reset the view

    glTranslatef(-1.5f, 0.0f, -6.0f);   // Move Left 1.5 units and into the screen 6.0

    glBegin(GL_TRIANGLES);
        glVertex3f( 0.0f, 1.0f, 0.0f);  // Top
        glVertex3f(-1.0,-1.0f, 0.0f);  // Bottom Left
        glVertex3f( 1.0f,-1.0f, 0.0f);  // Bottom Right
    glEnd();

    glTranslatef(3.0f, 0.0f, 0.0f);

    glBegin(GL_QUADS);  // Draw a quad
        glVertex3f(-1.0f, 1.0f, 0.0f);
        glVertex3f( 1.0f, 1.0f, 0.0f);
        glVertex3f( 1.0f,-1.0f, 0.0f);
        glVertex3f(-1.0f,-1.0f, 0.0f);
    glEnd();
}

```

I would greatly appreciate it if someone could help me resolve my issue.

# Answer
> 1 votes
Changed init's from:

```
glMatrixMode(GL_MODELVIEW);

```

to

```
glMatrixMode(GL_PROJECTION);

```

and added

```
glMatrixMode(GL_MODELVIEW);

```

to "renderGlScene(sf::Window \*app)" directly after "glClear(GL\_COLOR\_BUFFER\_BIT | GL\_DEPTH\_BUFFER\_BIT)" is called.

---
Tags: c++, opengl, sfml
---


# Question
Title: Java - Finding distance between player and tile in array
What is the best way performance wise to do this? When I click a tile I want it to get the distance and if I am close enough I can interact with the tile. One way would be to find the tile by doing mouse / tile width when I click correct? But then how would I get that tiles position? I know how to find the distance I just don't know how to get a certain tiles position from the array when I click it

```
public void checkDistance(GameContainer gc) {
    Input input = gc.getInput();

    float mouseX = input.getMouseX();
    float mouseY = input.getMouseY();

    double mousetileX = Math.floor(mouseX/tiles.tileWidth);
    double mousetileY = Math.floor(mouseY/tiles.tileHeight);

    //Distance code
    double lengthX = Math.abs(playerX - mousetileX);
    double lengthY = Math.abs(playerY - mousetileY);
    double distance = Math.sqrt((lengthX*lengthX)+(lengthY+lengthY));

    System.out.println(distance);
}

```

# Answer
This would be better if there was more information however i going to make the following assumptions:

* Your tiles are based off a 2d grid (from: slick2d and array)
* your using doubles to store position (cast if not true)

First of to find the tile you clicked on you would as you say divide your mouse position to your tile position so

```
double mousetileX = Math.floor(mousex/tileWidth);
double mousetileY = Math.floor(mousey/tileHeight);

```

**NOTE** you may need to take into account your view port offset if the map bigger than screen.

Now you have your click co-ordinates and you will already know your position co-ordinates there is a way to get the distance to them namely Pythagoras theorem

Basically states that on a right angle triangle the length of the hypotenuse (the longest side) is the square root of the sum of the squares of the other two sides. Wait a minute we dont have a triangle... sure we do.

If you draw a line between your coords then and then two more lines from that to meet at a 90 degree angle there it is.

To do this programmatically we first find the length of our first side.

```
//side 1
double lengthx = Math.abs(positionx-mousetileX); //abs to ensure positive.

//side2
double lengthy = Math.abs(positiony-mousetiley);

```

now we simply follow the formula

```
double distance = Math.sqrt((lengthx*lengthx)+(lengthy*lengthy));

```

And distance will be the length of the longest side ie your distance between your tiles.

**UPDATE**

Almost forgot what i have shown how to calculate is the relative distance between tiles on your grid not taking into account the tileWidth height to allow them to dynamically be resized etc.

**UPDATE2**

Also when calculating player position relative to your grid it is pretty similar to the mouse calculation.

```
double playertileX = Math.floor(playerx/tileWidth);
  double playertileY = Math.floor(playery/tileHeight);

```

Hope this helps
> 2 votes

---
Tags: java, tiles, slick
---


# Question
Title: Drawing 2D Grid in 3D View - Need help with method
I'm trying to draw a simple 2D grid for an editor, to able to navigate more clearly around the 3D space, but I can't render it:

Grid2D class, creates a grid of a certain size at a location and should just draw lines.

```
public class Grid2D : IShape
{

    private VertexPositionColor[] _vertices;

    private Vector2 _size;
    private Vector3 _location;

    private int _faces;

    public Grid2D(Vector2 size, Vector3 location, Color color)
    {
        float x = 0, y = 0;

        if (size.X < 1f)
        {
            size.X = 1f;
        }

        if (size.Y < 1f)
        {
            size.Y = 1f;
        }

        _size = size;
        _location = location;

        List<VertexPositionColor> vertices = new List<VertexPositionColor>();
        _faces = 0;

        for (y = -size.Y; y <= size.Y; y++)
        {
            vertices.Add(new VertexPositionColor(location + new Vector3(-size.X, y, 0), color));
            vertices.Add(new VertexPositionColor(location + new Vector3(size.X, y, 0), color));

            _faces++;
        }

        for (x = -size.X; x <= size.X; x++)
        {
            vertices.Add(new VertexPositionColor(location + new Vector3(x, -size.Y, 0), color));
            vertices.Add(new VertexPositionColor(location + new Vector3(x, size.Y, 0), color));

            _faces++;
        }

        _vertices = vertices.ToArray();
    }

    public void Render(GraphicsDevice device)
    {
        device.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, _vertices, 0, _faces);
    }

}

```

Like this:

```
+----+----+----+----+
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
+----+----+----+----+

```

Anyone knows what I'm doing wrong? If I add a Shape without texture, it's set automatically to VertexColorEnabled and TextureEnabled = false.

This is how I render it:

```
        foreach (RenderObject render in _renderObjects)
        {
            render.Effect.Projection = projection;
            render.Effect.View = view;
            render.Effect.World = world;

            foreach (EffectPass pass in render.Effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                try
                {
                    // Could be a Grid2D
                    render.Shape.Render(_device);
                }
                catch
                {
                    throw;
                }
            }
        }

```

Exception is thrown:

```
The current vertex shader declaration does not include all the elements required by the current Vertex Shader. Normal0 is missing.

```

Simply put, I can't figure out how to draw a few lines. I want to draw them one at a time and I guess that's the problem I haven't figured out, and even when I tried rendering vertices\[i\], vertices\[i+1\] and primitiveCount = 1, vertices = 2, and so on it didn't work either.

Any suggestions?

# Answer
> 1 votes
Problem was that I set the effect for this to .EnableDefaultLightning(); but I shouldn't.

and this works as the Render code:

```
device.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, _vertices, 0, _faces, VertexPositionColor.VertexDeclaration);

```

---
Tags: xna, c#, 2d, 3d, grid
---


# Question
Title: What should I do if my text exceeds my text render target boundaries?
I have a method for drawing strings in 3D that does the following:

* Set a render target
* Draw each character as a quadrangle using a orthographic projection to the render target
* Unset the render target
* Draw the render target texture using a perspective projection and a world transform

My problem is how to deal with strings whose characters length exceeds that of the render target dimensions? For example if I have string "This is a reallllllllllly long string" and the render target can't accommodate it, it will only capture "This is a realllll".

The render target (and its size) could be set each frame but wouldn't that be far too costly?

# Answer
Before rendering the text, compute its bounds. If the text would be too long horizontally, split the string you render into substrings. This can be done as an implementation detail of the text rendering API, so users don't have to know their string was too long to fit. If you employ a bin-packing technique to place each text substring in your render target (this one, for example, is simple and effective and this page describes some improves to it) you can fit quite a lot of text onto a single render target sheet, especially if you start getting fancy and trying to rotate some of the strings.

If you ever fill a render target sheet, create another one. You can't really resize render target textures -- you destroy them and recreate them, so simply creating a new one alongside your existing one is generally easier on computing resources.

Plus, it allows you to build a caching mechanism into your text rendering -- exploiting the fact that if a piece of text was rendered this frame it will probably be rendered again next frame, which can save you from having to re-rasterize a lot of text into your sheets.
> 3 votes

# Answer
Just resize the RenderTarget when you are sure the text won't fit, and keep the new size. Then calculate the text string rectangle bounds and draw only that portion of the RenderTarget.
> 1 votes

# Answer
I would suggest to make yourself a small function that calculates the length the text will take depending on the font and the size. Then make the render target big enough. That's how we deal with any type of text where I work. If the render target cannot be bigger, we scale down the font. And beyond let say a scale of 70% of the original size, we simply flag the text as too long (like put it in a bright red) to be able to quickly see when some text need to be reviewed.

Hope that helps.
> 1 votes

---
Tags: xna, rendertargets
---


# Question
Title: How to split a string with negative numbers using ActionScript 3.0
I'm having trouble loading my level. I'm using Ogmo to create my level then I import it. I have no problem converting 0's and 1's into an Array, but I can't figure out how to do the same for -1's. It separates the "-" and the "1". Any help would be great. I've posted my code and the XML files below EDIT: Uploaded new code.

```
levelXML = new XML(e.target.data);
        playerX = int(levelXML.Entities.Player.@x);
        playerY = int(levelXML.Entities.Player.@y);
        levelGrid = levelXML.Grid;
        levelGrid = levelGrid.split("\n").join("");
        levelTiles = levelXML.Tiles;
        levelTiles = levelTiles.split("\n").join("")
        tileArray = levelTiles.split(",")
        gridArray = levelGrid.split("");
        for(i = 0; i <= 34; i++)
        {
            levelArray[i] = new Array();
            for(j = 0; j <= 34; j++)
            {

                if(tileArray[j*35 + i] == 0)
                {
                    gridArray[j*35+i] = -1;

                }
                var currentSymbol = gridArray[j*35+i];
                levelArray[i][j] = currentSymbol;
                if(gridArray[j*35 + i] == 1)
                {
                    wall = new Wall;
                    addChild(wall);
                    wall.x = i*20 + 10;
                    wall.y = j*20 + 10;
                }
                else if(gridArray[j*35 + i] == -1)
                {
                    pellet = new Pellet;
                    addChild(pellet);
                    pellet.x = i*20 + 10;
                    pellet.y = j*20 + 10;
                }

            }
        }

```

I know the code is very dirty, but I needed a quick fix.

Grid exportMode="Bitstring"\> 11111111111111111111111111111111111 10000000000000000011000000000000001 10000000000000000011000000000000001 10011111001111110011001111110011001 10011111001111110011001111110011001 10011111001111110011001111110011001 10000000000000000000000000000000001 10000000000000000000000000000000001 10011111001100111111100110011111001 10011111001100000100000110011111001 10000000001100000100000110000000001 10000000001111100100111110000000001 11111111001111100100111110011111111 00000001001111100100111110010000000 00000001001100000000000110010000000 11111111001100000000000110011111111 00000000000000111111100000000000000 00000000000000100000100000000000000 11111111001100100000100110011111111 00000001001100111111100110010000000 00000001001100000000000110010000000 11111111001100111111100110011111111 10000000000000000100000000000000001 10000000000000000100000000000000001 10011111001111100100111110011111001 10000011000000000000000000011000001 10000011000000000000000000011000001 11110011001100111111100110011001111 11110011001100111111100110011001111 10000000001100000100000110000000001 10000000001100000100000110000000001 10011111111111100100111111111111001 10000000000000000000000000000000001 10000000000000000000000000000000001 11111111111111111111111111111111111

Tiles tileset="Tiles" exportMode="CSV"-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,0,0,0,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1 -1,-1,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1

# Answer
In case of the zeroes and ones, you have to split with `""`, but in case of the tile-numbers this doesn't work as it would create an array entry for `-` and `1` when the value should be `-1`. But luckily you have a delimiter `,` which you can use.

So instead of

```
levelTiles = levelTiles.split("\n").join("");
levelTiles = levelTiles.split(",").join("");
tileArray = levelTiles.split("");

```

Use:

```
levelTiles = levelTiles.split("\n").join(",");
tileArray = levelTiles.split(",");

```

A cleaner way to split (which also removes unnecessary white-space) could be done with a regular expression:

```
tileArray = levelTiles.replace(/\n\r?/g,",").split(/\s*,\s*/);

```

To split the Bitstring and get rid of the white-space I suggest you use this instead:

```
bitArray = bitString.replace(/\s+/g, "").split("");

```
> 4 votes

---
Tags: actionscript-3, xml
---


# Question
Title: Separating logic and data in browser game
I've been thinking this over for days and I'm still not sure what to do. I'm trying to refactor a combat system in PHP (...sorry.) Here's what exists so far:

* There are two (so far) types of entities that can participate in combat. Let's just call them players and NPCs. Their data is already written pretty well.
* When involved in combat, these entities are wrapped with another object in the DB called a `Combatant`, which gives them information about the particular fight. They can be involved in multiple combats at once.
* I'm trying to write the logic engine for combat by having combatants injected into it.
* I want to be able to mock everything for testing.

In order to separate logic and data, I want to have two interfaces / base classes, one being `ICombatantData` and the other `ICombatantLogic`. The two implementers of data will be one for the real objects stored in the database, and the other for my mock objects.

I'm now running into uncertainties with designing the *logic* side of things. I can have one implementer for each of players and NPCs, but then I have an issue. A combatant needs to be able to return the entity that it wraps. Should this getter method be part of logic or data? I feel strongly that it should be in data, because the logic part is used for *executing* combat, and won't be available if someone is just looking up information about an upcoming fight. But the data classes only separate mock from DB, not player from NPC. If I try having two child classes of the DB data implementer, one for each entity type, then how do I architect that while keeping my mocks in the loop? Do I need some third interface like `IEntityProvider` that I inject into the data classes?

Also with some of the ideas I've been considering, I feel like I'll have to put checks in place to make sure you don't mismatch things, like making the logic for an NPC accidentally wrap the data for a player. Does that make any sense? Is that a situation that would even be possible if the architecture is correct, or would the right design prohibit that completely so I don't need to check for it?

If someone could help me just layout a class diagram or something for this it would help me a lot. Thanks.

## edit

Also useful to note, the mock data class doesn't really need the `Entity`, since I'll just be specifying all the parameters like combat stats directly instead. So maybe that will affect the correct design.

# Answer
Part of the way I've approached this in the past is, rather than having completely separate representations for players and NPCs while requiring that they both implement a common interface, driving toward convergence of representation between them to the greatest extent that I can, as by subclassing them from a common `Character` model into which I push as much about them as makes any sense to generalize. This helps avoid issues with running NPC operations on players and such by making operations more generally applicable, since there's less natural tendency for the representations to diverge than if they're completely independent implementations. Basic leveraging of polymorphism helps handle the cases that have to diverge (for instance, if you made your `CombatantLogic` responsible for handling what happens when somebody dies, you would have to do typechecking to make sure you used the right logic; so don't, have players and NPCs implement separate, appropriate `die()` methods).

I agree that your `Entity` is part of data. However, building on what I was saying, I would actually tend toward removing or limiting the role of your `CombatantData` in favor of having the combat logic draw values directly from the `Entity`, perhaps with `CombatantData` only storing expensive, single-combat-specific calculated values. Your test mockups would then be oriented more toward providing fake `Entity` models than toward populating `CombatantData`. (Having `CombatantData` duplicate a lot of information from the `Entity` bothers me in much the same way that a denormalized database does. However, if you believe in the Law of Demeter, which I passionately do not, you won't want to do things the way I'm suggesting. Of course, if you believe in the Law of Demeter, I'm not sure your `CombatantData` should even provide access to the `Entity`.)
> 1 votes

---
Tags: architecture, php, interface
---


# Question
Title: Adding tolerance to a point in polygon test
I've been using this method which was taken from Game Coding Complete to detect whether a point is inside of a polygon. It works in almost every case, but is failing on a few edge cases, and I can't figure out the reason.

For example, given a polygon with vertices at (0,0) (0,100) and (100,100), the algorithm is returning:

* True for any point strictly inside the polygon
* False for any of the vertices
* False for (0, 50) which lies on one of the edges of the polygon
* **True** (?) for (50,50) which is also on one of the edges of the polygon

I'd actually like to relax the algorithm so that it returns true in all of these cases. In other words, it should return true for points that are strictly inside, for the vertices themselves, and for points on the edges of the polygon.

If possible I'd also like to give it enough tolerance so that it always tend towards "true" in face of floating point fluctuations. For example, I have another method, that given a line segment and a point, returns the closest location *on* the line segment to the given point.

Currently, given any point outside the polygon and one of its edges, there are cases where the result is categorized as being inside by the method above, while other points are considered outside. I'd like to give it enough tolerance so that it always returns true in this situation.

The way I've currently solved the problem is an hack, which consists of using an external library to inflate the polygon by a few pixels, and performing the tests on the inflated polygon, but I'd really like to replace this with a proper solution.

# Answer
> 4 votes
Since the algorithm already parses all edges of the polygon to see how many times a ray cast from `test` crosses them, I think it's reasonable to add a check to see whether `test` lies on the edge exactly (or within an epsilon).

In order to avoid too much additional complexity (the usual point - segment distance computation is really awful), I suggest approximating the edge to an extremely thin ellipse and see whether `test` is on that ellipse. This is the resulting code (only the inner loop shown):

```
oldPoint = polygon[points-1];
float oldSqDist = sqlength(oldPoint - test);

for (unsigned int i=0 ; i < points; i++)
{
    newPoint = polygon[i];
    float newSqDist = sqlength(newPoint - test);

    if (oldSqDist + newSqDist + 2.0f * std::sqrt(oldSqDist * newSqDist) - sqlength(newPoint - oldPoint) < EPSILON)
        return true;

    if (newPoint.x > oldPoint.x)
    {
        left = oldPoint;
        right = newPoint;
    }
    else
    {
        left = newPoint;
        right = oldPoint;
    }

    if ((newPoint.x < test.x) == (test.x <= oldPoint.x)
       && (test.y-left.y) * (right.x-left.x)
        < (right.y-left.y) * (test.x-left.x) )
    {
        inside=!inside;
    }

    oldPoint = newPoint;
    oldSqDist = newSqDist;
}

```

Where `sqlength()` is your favourite way of doing `x * x + y * y`. I tested the code with `EPSILON = 1e-10f` and got good results. In real life you should have `EPSILON` vary relatively to the size of your polygon.

# Answer
> 1 votes
A common approach to this sort of thing is to add epsilons to the floating-point comparisons. I'm not completely sure how to do this in the code you linked, since it seems that it's flipping the inside/outside bit as a result of some comparisons - so perhaps you'd need the epsilon to be positive when currently inside, and negative when outside, or vice versa. The idea would be to make the compares forgiving in the direction that tends to make the result 'inside'.

# Answer
> 1 votes
May I suggest another approach? As described in Real Time Collision Detection, to test if a point is inside a convex polygon oriented counter-clockwise, one fast way is to subdivide in half the polygon and check if the triangle formed by v0 (the first vertex of the poly), vk (k = n/2, with n the number of vertices) and p is oriented CCW. If so we can check again, incrementing k and see if the triangle is again CCW or not. If not the point lies inside the polygon, if not we must check again. The test is implemented as follow (just copying from the text):

```
int PointInConvexPolygon(Point p, int n, Point v[])
{
    int low = 0, high = n;
    do
    {
        int mid = (low + high)/2;
        if (TriangleIsCCW(v[0], v[mid], p)) low = mid;
        else high = mid;
    }
    while (low + 1 < high);
    if (low == 0 || high == n) return 0;
    return TriangleIsCCW(v[low], v[high], p);
}

```

http://pastebin.com/QkHi1Hrg

Here `TriangleIsCCW` checks if p lies on the left or on the right the segment formed by v\[low\] and v\[high\], and can be implemented as a method that checks if the determinant |ax ay 1| |bx by 1| |cx cy 1| with A (ax, ay), B (bx, by), C (cx, cy) the points checked. If the determinant is positive, the points are oriented CCW, if is 0 they are collinear. This can be used for particular cases as the points lying on the edge or on the vertex.

---
Tags: mathematics, geometry
---


title: Game speed cubic growth

text:
# Question
Title: Game speed cubic growth
Is it possible, using delta in my update method to increase a game speed variable exponentially on cubic growth (the blue line below)

My maths isn't great so I'm not sure how the formula would be put into practice using a `float gameSpeed` and delta in an update method `-(void) update:(ccTime)delta` I think I would also need a value to control the speed of the growth too?

# Answer
> 2 votes
Probably the most robust way is to store a linearly-growing `gameTime` value that you can update by just adding the delta to it each frame, then set `gameSpeed = someConstant * pow(gameTime, 3.0)` each frame.

But if you want to be able to do something interesting like changing the power continuously in real time, you could use the derivative: if y = t^n (in your case n = 3) then dy = nt^(n-1) dt = ny^((n-1)/n) dt, so you'd implement an update method like

```
power = 3.0;   // Or whatever power you want; it could even change over time
gameSpeed += someConstant * delta * power * pow(gameSpeed, (power - 1.0) / power);

```

That should cause `gameSpeed` to grow approximately as time cubed, but you could also alter the power to increase or decrease the rate of acceleration (or make it slow down again, using a negative power).

---
Tags: mathematics, iphone, cocos2d-iphone, cocos2d
---


# Question
Title: How can I move a polygon edge 1 unit away from the center?
Let's say I have a polygon class that is represented by a list of vector classes as vertices, like so:

```
 var Vector  = function(x, y) { this.x = x; this.y = y; },
     Polygon = function(vectors) { this.vertices = vectors; };

```

Now I make a polygon (in this case, a square) like so:

```
var poly = new Polygon([
    new Vector(2, 2),
    new Vector(5, 2),
    new Vector(5, 5),
    new Vector(2, 5)
]);

```

So, the top edge would be `[poly.vertices[0], poly.vertices[1]]`.

I need to stretch this polygon by moving each edge away from the center of the polygon by one unit, along that edge's normal. The following example shows the first edge, the top, moved one unit up:

The final polygon should look like this new one:

```
var finalPoly = new Polygon([
    new Vector(1, 1),
    new Vector(6, 1),
    new Vector(6, 6),
    new Vector(1, 6)
]);

```

**It is important that I iterate, moving one edge at a time**, because I will be doing some collision tests after moving each edge.

Here is what I tried so far (simplified for clarity), which fails triumphantly:

```
for(var i = 0; i < vertices.length; i++) {
    var a = vertices[i],
        b = vertices[i + 1] || vertices[0]; // in case of final vertex

    var ax = a.x,
        ay = a.y,
        bx = b.x,
        by = b.y;

    // get some new perpendicular vectors
    var a2 = new Vector(-ay, ax),
        b2 = new Vector(-by, bx);

    // make into unit vectors
    a2.convertToUnitVector();
    b2.convertToUnitVector();

    // add the new vectors to the original ones
    a.add(a2);
    b.add(b2);

    // the rest of the code, collision tests, etc.
}

```

This makes my polygon start slowly rotating and sliding to the left, instead of what I need.

Finally, the example shows a square, but the polygons in question could be anything. They will always be convex, and always with vertices in clockwise order.

# Answer
> 1 votes
Your polygon is rotating to the left because the unit vectors you are adding have the opposite sign of your x component (gotten when you create the perpendicular vectors). Adding those to your original vectors will shift them counter clockwise (to the left for positive Y and to the right for negative Y values of your original vectors).

I assume you're trying to create the perpendicular vectors to make sure you increase the original vectors along the normal to the edge. I don't think you need to do that, you should probably just create UnitVectors for the original vectors and add them to the originals.

This still might not get the whole edge to move 1 exact unit away from the center. If that's the more important part of what you're trying to achieve, you might want to get the center point of the edge (by averaging the vectors together), getting the UnitVector for that, and then adding that UnitVector to each of your original vectors.

# Answer
> 2 votes
I think the part where you `get some new perpendicular vectors` looks strange because `a` and `b` are positions, not vectors, and it doesn't make sense to get the perpendicular of a position.

I think you should probably start by doing `a-b` (or `b-a` depending on the vertex order, not sure which one now) to get the tangent of the edge, then get the perpendicular of that tangent, which will be the edge normal, and finally apply the same normal to both vertices. Don't forget to normalize first though.

Still I'm not sure the results will be as you want, because polygon offsetting is tricky business. Check this question for more information on the subject.

---
Tags: vector, computational-geometry
---


# Question
Title: Multiplication for MVP matrices: Any benefits to doing so within the vertex shader?
I'd like to understand under what circumstances (if any) it is worth doing MVP matrix multiplication *inside* a vertex shader.

The vertex shader is run once per vertex, and a single mesh typically contains many vertices. All MVP inputs remain the same for each vertex in the vertex batch relating to a given draw call (model). Surely then, you're always better off keeping the multiplications in the client code, such that you pass in the whole MVP precalculated as a uniform? (avoiding redundant ops between individual vertices)

# Answer
If all you need to transform is the vertex positions, then I agree that there's no reason not to precompute the entire MVP matrix.

If you need to transform things like normal vectors and tangent vectors as well, you'll need more matrices. Probably your normals and tangents should end up in world space, or perhaps view space, so you'll want to transform them by just the local-to-world matrix, or the modelview matrix, but not the projection matrix.

Given this, it's possible to compute the positions in two ways - either by using one matrix multiply by a precomputed MVP matrix, or by doing two matrix multiplies, one going from local to world (the same matrix as for tangent vectors) and then from world to clip. If you use the MVP, you have to set two matrices per draw call, the MVP and the local-to-world matrix. If you use the second method, you only have to set the local-to-world matrix per draw call, since the world-to-clip matrix is constant for the whole frame. It's *possible* that setting one matrix vs two could make a difference in performance or memory usage in some cases. That's the only reason I can think of that using a precomputed MVP matrix might not be best.

All in all, I'd probably just use the precomputed MVP matrix unless you find a compelling reason to try it the other way.
> 5 votes

---
Tags: opengl, shaders, matrix, opengl-es2
---


title: Cocos2D 2.0 - masking a sprite

text:
# Question
Title: Cocos2D 2.0 - masking a sprite
I have read this tutorial about how to mask sprites using Cocos2D 2.0. http://www.raywenderlich.com/4428/how-to-mask-a-sprite-with-cocos2d-2-0

But the author talks about OpenGL ES textures and vertices as they were common knowledge. My knowledge about OpenGl is zero raised to infinity.

All I want is to use a rectangle to mask a sprite to it. How I would do in Photoshop using a rectangle as mask (yes, I want to clip a sprite to the rectangle bounds and no, I do not want to use the ClippingNode solution, that do not works for animation/scaling etc.).

So, can you guys translate the klingon language used in this tutorial and tell how a solid rectangle can be used to mask a sprite in Cocos2D?

I am desperate, as my username states. I am searching this for a week and have tried several solutions without satisfactory results. Please help me.

Thanks!

# Answer
Like you, I'm not very comfortable with OpenGL. Unlike you this tuto helped me, failing to fully understand, to create one component for one of my project. So I'll try to explain it to you as clearly as I can.

The first thing is that you don't have to worry about the mask's shader. It is just a litle "program" which describe the execution pipeline to produce the mask. There is already wrote and it works (cf: Mask.fsh). Just put it into your project.

Then create and init the mask which will be put as a texture, and associate it to the shader:

```
- (id)initWithFile:(NSString *)file
{
    self = [super initWithFile:file];
    if (self) {

        // Create your rectangle mask
        _maskTexture = [[[CCTextureCache sharedTextureCache] addImage:@"CalendarMask.png"] retain];

        // Create and init the shader
        self.shaderProgram =
        [[[GLProgram alloc]
          initWithVertexShaderFilename:@"Shaders/PositionTextureColor.vert"
          fragmentShaderFilename:@"Mask.frag"] autorelease];
        [shaderProgram_ addAttribute:kCCAttributeNamePosition index:kCCAttribPosition];
        [shaderProgram_ addAttribute:kCCAttributeNameColor index:kCCAttribColor];
        [shaderProgram_ addAttribute:kCCAttributeNameTexCoord index:kCCAttribTexCoords];

        [shaderProgram_ link];
        [shaderProgram_ updateUniforms];

        // Gets the location of the texture and mask uniforms
        _textureLocation = glGetUniformLocation( shaderProgram_->program_, "u_texture");
        _maskLocation = glGetUniformLocation( shaderProgram_->program_, "u_mask");
    }

    return self;
}

```

To finish override the draw method with this:

```
- (void)draw
{
    CC_NODE_DRAW_SETUP();

    ccGLEnableVertexAttribs(kCCVertexAttribFlag_PosColorTex);
    ccGLBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    [shaderProgram_ setUniformForModelViewProjectionMatrix];

    glActiveTexture(GL_TEXTURE0);
    glBindTexture( GL_TEXTURE_2D, [texture_ name] );
    glUniform1i(textureLocation_, 0);

    glActiveTexture(GL_TEXTURE1);
    glBindTexture( GL_TEXTURE_2D, [maskTexture_ name] );
    glUniform1i(maskLocation_, 1);

#define kQuadSize sizeof(quad_.bl)
    long offset = (long)&quad_;

    // vertex
    NSInteger diff = offsetof( ccV3F_C4B_T2F, vertices);
    glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (void*) (offset + diff));

    // texCoods
    diff = offsetof( ccV3F_C4B_T2F, texCoords);
    glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff));

    // color
    diff = offsetof( ccV3F_C4B_T2F, colors);
    glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff));

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glActiveTexture(GL_TEXTURE0);
}

```

This will just apply your texture as the mask of the sprite. You don't need another step. you can add sprites as children of this one and they will be masked automatically.

There is only 3 steps to retain:

1. Adding the shader (is already made)
2. Initialized the shader and keep track of the mask's texture and location
3. Override the draw method with the given method

I hope it'll help you
> 2 votes

---
Tags: cocos2d-iphone, cocos2d
---


title: Falling images that can be pressed

text:
# Question
Title: Falling images that can be pressed
In my cocos2d app I am trying to make images fall from the top of the screen and detect when they are pressed. I am having a hard time. Can anyone help me achieve this? Thanks.

# Answer
Once you have implemented some touch delegate you can easely tell if you touched your sprite or not using bounding boxes, doing something like:

```
    if (CGRectContainsPoint(touchPoint, [sprite boundingBox])){

}

```
> 2 votes

# Answer
I am going to do a language and platform independent approach here.

All images should be represented as rectangles. Rectangles are usually just 4 elements long arrays that look like this: `[x, y, width, height]`.

`x` and `y` represent the position of the image. If you want the image to have a falling effect, ie to move downwards, they you will want to increase the `y` coordinate gradually (the `y` axis increases "downwards" in computer graphics, remember that).

The `width` and `height`, obviously, represent the dimensions of the image.

A **click** can be represented by two numbers, just the `x` and `y`, as it is actually just a point in space, it doesn't have any dimensions.

Now, your problem is essentially checking whether the click happened *inside* the image. How do you do that?

Well, like this:

```
//xc = click x
//yc = click y
//rect = [x, y, width, height]

if (xc >= rect[0] && xc <= rect[0] + rect[2] && yc >= rect[1] && yc <= rect[1] + rect[3])
{
    //Click happened.
}
else
{
    //The click was outside of this particular image.
}

```

If you don't understand the code, tell me what is bothering you in a comment and I will explain further.
> 0 votes

---
Tags: cocos2d-iphone, ios, cocos2d
---


# Question
Title: Blender 2.6: How to Merge the Pros of Meshes and Surfaces
there are two interesting kinds of objects: Meshes and Surfaces. Each of them offers very cool features.

## Object Type Specific Features

### Nice Features of Surfaces:

*(for example)*

* They're as scalable as vector graphics (*really nice!*)
* You can build winding things real simply.

### Nice Features of Meshes:

*(for example)*

* You can build organic things really good using the Sculpt Mode and a graphic tablet.
* You can use some special things like Physics.

## My Question

There are things for which Surfaces are better and things for which Meshes are better. But how can I use *both* the best features of Surfaces and the best features of Meshes on *one* object *at once*?

*For example:* How can I use Physics (*like on Meshes*) *on* lossless scalable objects (*like Surfaces*)?

Thanks.

# Answer
> 1 votes
I've always just leaned on mesh modifiers. I find meshes easier to work with in just about every way. If I ever use a curve, it's probably as an animation guideline rather than as a static shape.

> Advantage of Curve - they are scalable as vector graphics.

You can smooth meshes out by applying a `Subsurf` modifier. With an appropriately low resolution base mesh, it would work similarly to a Surface, with the added advantage of not requiring square patches like NURBS. See this subdivisionmodeling tutorial for examples of how Subdivision surfaces behave like, but better than, NURBS surfaces.

> Advantage of Curve - you can build winding things really simply.

Create a mesh. Optionally duplicate it using an Array modifier (e.g. you make one stairstep, then Array it out into a bunch of stairs) Then use a `Screw`, `Curve`, `Lattice`, or `Deform` modifier to guide it along a curved path.

---
Tags: 3d-meshes, blender
---


# Question
Title: Level selection view - similiar to Angry Bird's
I am making game and need to prepare view for level selection. Could you recommend me some opensource library which could I use? I need icons to vibrate after long pressing one of them, some callbacks after choosing them, possibility to prepare custom icon's view, page control and horizontal scrolling. I was trying to use OpenSpringBoard but weirdly couldn't see scrollview and pagecontrol working in this project - it seems that there's possibility to use only one page. On the other hand, myLauncher(https://github.com/dlinsin/myLauncher) isn't so easy to include in project, as I need a seperate view with some delegate methods.

I need to be compatible with \>iOS 4.2

# Answer
I you are making a game you really should use some graphic engine like cocos-2d (which uses opengl for rendering) and not using standard iOs views.

Here an example the angry bird menu done with cocos-2d : http://www.youtube.com/watch?v=kZ\_d\_B-PjyY
> 1 votes

---
Tags: ios, objective-c, cocoa
---


# Question
Title: Are native code obfuscations needed to prevent piracy of Android games?
Is the copyright protection and enforcement of Android apps written in Java sufficient or should I be relying on a native implementation to use machine code obfuscating techniques in order to prevent piracy of my game?

Please provide an answer with supporting examples of games which use either technique.

# Answer
I don't have examples readily available, but obfuscating your code will not really provide any significant advantage in preventing piracy of your application. Piracy is typically accomplished through hacks that bypass copy protection or DRM checks, which can be done at the machine code or VM opcode level.

No amount of obfuscation of the higher level code prior to letting it get compiled to machine code or the intermediate representation used by a VM will help you at that point.

I would not bother.
> 7 votes

# Answer
If you are still interested the Android SDK provides a native offuscation tool : ProGuard.

And during Google IO 12 they have announced a new “application encryption” feature (DRM) but detail are still unknown.
> 2 votes

# Answer
to add onto the other answers, the way to get people to pay for your game (not pirate it) is one, use ads, two, make people want to buy it: make it good and give them a free trial so they can see if they like it. That could even mean giving it out for free and letting them 'donate'. You could also use things like in app purchases (they could be circumvented, but its trickier) and online features that require purchasing to take advantage of; to name a few.
> 1 votes

---
Tags: android, ndk
---


# Question
Title: Is using a dedicated thread just for sending gpu commands a good idea?
The most basic game loop is like this :

```
while(1)
{
   update();
   draw();
   swapbuffers();
}

```

This is very simple but have a problem : some drawing commands can be blocking and cpu will wait while he could do other things (like processing next update() call).

Another possible solution i have in mind would be to use two threads :

one for updating and preparing commands to be sent to gpu, and one for sending these commands to the gpu :

```
//first thread
while(1)
{
   update();
   render(); // use gamestate to generate all needed triangles and commands for gpu
             // put them in a buffer, no command is send to gpu
             // two buffers will be used, see below
   pulse(); //signal the other thread data is ready
}

//second thread
while(1)
{
   wait();              // wait for second thread for data to come
   send_data_togpu();   // send prepared commands from buffer to graphic card
   swapbuffers();
}

```

also : two buffers would be used, so one buffer could be filled with gpu commands while the other would be processed by gpu.

Do you thing such a solution would be effective ? What would be advantages and disadvantages of such a solution (especially against a simpler solution (eg : single threaded with triple buffering enabled) ?

---

EDIT : I have taken a real example to show a situation where there would be an advantage :

Let's say i have a scene which consist of rendering same entity a lot of times (like in a RTS) :

in this example :

* updating world take 100 ms (because there is lot of entities)
* sending commands to gpu almost nothing (only calls to gldrawelements for the same entity, vertex buffers only sent once) (almost 1ms)
* scene rendering by gpu is also heavy, take 100 ms

total = ~200 ms (or 5 fps)

I dont think gpu could be draw something during update procedure because gpu doesnt have any idea when scene start (and cant assume glclear = beginning of scene rendering)

---

now lets say the system is using two independant threads :

* update take 100ms
* sending cmds take 1ms
* next update can already start no need to wait for gpu
* scene rendering take 100ms

total = ~100 ms (actually a little more than this because of synchronisation)

# Answer
The fact that multithreaded rendering is a major feature in D3D11 suggests that it indeed can be useful to have multiple threads for generating the GPU command stream. :) Indeed the CPU is "just" storing a sequence of commands for the GPU to execute later, but that doesn't mean it's a trivial amount of work.

Incidentally, with an API like D3D or OpenGL it's mostly not necessary to explicitly double-buffer things yourself. The driver is already internally double-buffering the command streams (or it's using a ring buffer or some such).

Besides, rendering the scene usually also involves doing a bunch of CPU work like updating scene graph node transforms, frustum/occlusion culling, LOD selection, and so on beyond solely queuing up GPU commands. As game worlds become more complex it starts making a lot of sense to multithread all this stuff.
> 5 votes

# Answer
I can't authoritatively say that this wouldn't work, but it seems unlikely to be of benefit as the GPU is already a separate piece of hardware that runs in parallel with the CPU. The data just gets piped down to it as appropriate and even the final display call is often buffered up in my experience rather than being a blocking call. Therefore it would be surprising if any significant rendering commands held up the CPU to the extent where threading would help you.
> 3 votes

---
Tags: graphics, game-loop, multithreading, double-buffering
---


# Question
Title: Is the June 2010 DX SDK really the latest?
I have not been involved in game development, using the DirectX SDK, since around 2008. From the looks of it, the June 2010 release, of the DirectX SDK, is still the latest release. This release is more than two years ago, based on the name. Is this still the latest release, or has there been a naming convention change and I am missing something newer? I've seen mention of it being rolled into a Windows SDK, so I am confused and figured I would come here to ask.

Thanks

# Answer
> 5 votes
Yes, it's the latest version for Windows 7/Vista. In Windows 8 it has been merged with the Windows SDK you mentioned.

More information on the merge into Windows SDK here...

---
Tags: directx
---


title: XNA 2D Collision with specific tiles

text:
# Question
Title: XNA 2D Collision with specific tiles
I am new to game programming and to these sites for help. I am making a 2D game but I can't seem to get the collision between my character and certain tiles. I have a map filled with grass tiles and water tiles and I want to keep my character from walking on the water tiles. I have a Tiles class that I use so that the tiles are objects and also has the collision method in it, a TileEngine class used create the map and it also holds a list of Tiles, and the class James which is for my character. I also have a Camera class that centers the camera on my character if that has anything to do with the problem. The character's movement is intended to be restricted to 4 directions(up, down, left, right). As an extra note, the bottom right water tile does have collision, but the collision does not occur for any of the other water tiles.

Here is my TileEngine class

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Test2DGame2
{
 class TileEngine : Microsoft.Xna.Framework.Game
 {
    //makes a list of Tiles objects
    public List<Tiles> tilesList = new List<Tiles>();

    public TileEngine()
    {}

    public static int tileWidth = 64;
    public static int tileHeight = 64;

    public int[,] map = {
          {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
          {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
          {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,},
          {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,},
                 };

    public void drawMap(SpriteBatch spriteBatch)
    {
        for (int y = 0; y < map.GetLength(0); y++)
        {
            for (int x = 0; x < map.GetLength(1); x++)
            {
                //make a Rectangle
                tilesList[map[y, x]].rectangle = new Rectangle(x * tileWidth, y *        tileHeight, tileWidth, tileHeight);

                //draw the Tiles objects
                spriteBatch.Draw(tilesList[map[y, x]].texture,
                    tilesList[map[y, x]].rectangle,
                    Color.White);
            }
        }
    }
 }
}

```

Here is my Tiles class

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Test2DGame2
{
 class Tiles
 {
    public Texture2D texture;
    public Rectangle rectangle;

    public Tiles(Texture2D texture)
    {
        this.texture = texture;
    }

    //check to see if james collides with the tile from the right side
    public void rightCollision(James james)
    {
           if (james.GetBounds().Intersects(rectangle))
           {
               james.position.X = rectangle.Left - james.front.Width;
           }
    }
 }
}

```

I have a method for rightCollision because I could only figure out how to get the collisions from specifying directions.

and here is the James class for my character

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Test2DGame2
{
 class James
 {
    public Texture2D front;
    public Texture2D back;
    public Texture2D left;
    public Texture2D right;
    public Vector2 center;
    public Vector2 position;

    public James(Texture2D front)
    {
        position = new Vector2(0, 0);
        this.front = front;
        center = new Vector2(front.Width / 2, front.Height / 2);
    }

    public James(Texture2D front, Vector2 newPosition)
    {
        this.front = front;
        position = newPosition;
        center = new Vector2(front.Width / 2, front.Height / 2);
    }

    public void move(GameTime gameTime)
    {

        KeyboardState keyboard = Keyboard.GetState();
        float SCALE = 20.0f;
        float speed = gameTime.ElapsedGameTime.Milliseconds / 100.0f;

        if (keyboard.IsKeyDown(Keys.Up))
        {
            position.Y -=speed * SCALE;
        }
        else if (keyboard.IsKeyDown(Keys.Down))
        {
            position.Y += speed * SCALE;
        }
        else if (keyboard.IsKeyDown(Keys.Left))
        {
            position.X -= speed * SCALE;
        }
        else if (keyboard.IsKeyDown(Keys.Right))
        {
            position.X += speed * SCALE;
        }
    }

    public void draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(front, position, null, Color.White, 0, center, 1.0f, SpriteEffects.None, 0.0f);
    }

    //get the boundingbox for James
    public Rectangle GetBounds()
    {
        return new Rectangle(
            (int)position.X,
            (int)position.Y,
            front.Width, front.Height);
    }
 }
}

```

# Answer
> 1 votes
For the most basic form of collision detection, you need to maintain a "bounding box" around objects that should have collision. For example, you need to maintain a rectangle around James and around each water tile. These rectangles serve as the bounding boxes used to determine if collision is occurring. On each update, you can check to see if any points of James' bounding box are contained within the bounds of the water tile bounding boxes.

It looks like you're doing that. However, you can simply store the previous position of James prior to each position update and collision detection. That way, you can move James back to whatever position he was in if his bounds intersect with the bounds of a water tile.

For example (pseudo code):

```
Position jamesPosition = james.Position;

james.Move(x, y);

Rectangle jamesBounds = james.Bounds;
Rectangle tileBounds = tile.Bounds;

if(jamesBounds.Intersects(tileBounds))
    james.Position = jamesPosition;

```

A better way would probably be not to move James, but to calculate the position where he would move, do the collision detection, and then move him only if there was no collision.

Check this out too: Microsoft XNA Platformer Example, is the Collsion Detection implemented accurately?

**EDIT**

`tilesList[map[y, x]].rectangle = new Rectangle(`

`map[y,x]` will evaluate to 0 or 1 based on the values of your matrix. So, basically, you're only accessing `tilesList[0]` and `tilesList[1]`. Rectangles are being created and drawn properly, but the values of the `Tiles` at index 0 and index 1 of `tilesList` are being overwritten on each update.

---
Tags: xna, 2d, collision-detection, sprites, tiles
---


# Question
Title: Multiple setInterval in a HTML5 Canvas game
I'm trying to achieve multiple animations in a game that I am creating using Canvas (it is a simple ping-pong game). This is my first game and I am new to canvas but have created a few experiments before so I have a good knowledge about how canvas work.

First, take a look at the game here. The problem is, when the ball hits the paddle, I want a burst of n particles at the point of contact but that doesn't came right. Even if I set the particles number to 1, they just keep coming from the point of contact and then hides automatically after some time.

Also, I want to have the burst on every collision but it occurs on first collision only. I am pasting the code here:

```
//Initialize canvas
var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    W = window.innerWidth,
    H = window.innerHeight,
    particles = [],
    ball = {},
    paddles = [2],
    mouse = {},
    points = 0,
    fps = 60,
    particlesCount = 50,
    flag = 0,
    particlePos = {};

canvas.addEventListener("mousemove", trackPosition, true);

//Set it's height and width to full screen
canvas.width = W;
canvas.height = H;

//Function to paint canvas
function paintCanvas() {
    ctx.globalCompositeOperation = "source-over";
    ctx.fillStyle = "black";
    ctx.fillRect(0, 0, W, H);
}

//Create two paddles
function createPaddle(pos) {
    //Height and width
    this.h = 10;
    this.w = 100;

    this.x = W/2 - this.w/2;
    this.y = (pos == "top") ? 0 : H - this.h;

}

//Push two paddles into the paddles array
paddles.push(new createPaddle("bottom"));
paddles.push(new createPaddle("top"));

//Setting up the parameters of ball
ball = {
    x: 2,
    y: 2,
    r: 5,
    c: "white",
    vx: 4,
    vy: 8,
    draw: function() {
        ctx.beginPath();
        ctx.fillStyle = this.c;
        ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false);
        ctx.fill();
    }
};

//Function for creating particles
function createParticles(x, y) {
    this.x = x || 0;
    this.y = y || 0;

    this.radius = 0.8;

    this.vx = -1.5 + Math.random()*3;
    this.vy = -1.5 + Math.random()*3;
}

//Draw everything on canvas
function draw() {
    paintCanvas();
    for(var i = 0; i < paddles.length; i++) {
        p = paddles[i];

        ctx.fillStyle = "white";
        ctx.fillRect(p.x, p.y, p.w, p.h);
    }

    ball.draw();
    update();
}

//Mouse Position track
function trackPosition(e) {
    mouse.x = e.pageX;
    mouse.y = e.pageY;
}

//function to increase speed after every 5 points
function increaseSpd() {
    if(points % 4 == 0) {
        ball.vx += (ball.vx < 0) ? -1 : 1;
        ball.vy += (ball.vy < 0) ? -2 : 2;
    }
}

//function to update positions
function update() {

    //Move the paddles on mouse move
    if(mouse.x && mouse.y) {
        for(var i = 1; i < paddles.length; i++) {
            p = paddles[i];
            p.x = mouse.x - p.w/2;
        }
    }

    //Move the ball
    ball.x += ball.vx;
    ball.y += ball.vy;

    //Collision with paddles
    p1 = paddles[1];
    p2 = paddles[2];

    if(ball.y >= p1.y - p1.h) {
        if(ball.x >= p1.x && ball.x <= (p1.x - 2) + (p1.w + 2)){
            ball.vy = -ball.vy;
            points++;
            increaseSpd();

            particlePos.x = ball.x,
            particlePos.y = ball.y;
            flag = 1;
        }
    }

    else if(ball.y <= p2.y + 2*p2.h) {
        if(ball.x >= p2.x && ball.x <= (p2.x - 2) + (p2.w + 2)){
            ball.vy = -ball.vy;
            points++;
            increaseSpd();

            particlePos.x = ball.x,
            particlePos.y = ball.y;
            flag = 1;
        }
    }

    //Collide with walls
    if(ball.x >= W || ball.x <= 0)
        ball.vx = -ball.vx;

    if(ball.y > H || ball.y < 0) {
        clearInterval(int);
    }

    if(flag == 1) {
        setInterval(emitParticles(particlePos.x, particlePos.y), 1000/fps);
    }

}

function emitParticles(x, y) {

    for(var k = 0; k < particlesCount; k++) {
        particles.push(new createParticles(x, y));
    }

    counter = particles.length;

    for(var j = 0; j < particles.length; j++) {
        par = particles[j];

        ctx.beginPath();
        ctx.fillStyle = "white";
        ctx.arc(par.x, par.y, par.radius, 0, Math.PI*2, false);
        ctx.fill();

        par.x += par.vx;
        par.y += par.vy;

        par.radius -= 0.02;

        if(par.radius < 0) {
            counter--;
            if(counter < 0) particles = [];
        }

    }
}

var int = setInterval(draw, 1000/fps);

```

Now, my function for emitting particles is on line 156, and I have called this function on line 151. The problem here can be because of I am not resetting the `flag` variable but I tried doing that and got more weird results. You can check that out here.

By resetting the `flag` variable, the problem of infinite particles gets resolved but now they only animate and appear when the ball collides with the paddles. So, I am now out of any solution.

# Answer
> 2 votes
This for next loop is italising the particle every frame, this needs to be outside the function

```
function emitParticles(x, y) {

    for(var k = 0; k < particlesCount; k++) {
        particles.push(new createParticles(x, y));
    }

```

You need to wrap an if statement around this otherwise an exception error occurs

```
 if (par.radius > 0) {
     ctx.arc(par.x, par.y, par.radius, 0, Math.PI*2, false);
 }

```

You don't need do it like this.

```
if(flag == 1) {
    setInterval(emitParticles(particlePos.x, particlePos.y), 1000/fps);
}

```

Do this instead:

```
if(flag == 1) {
    // initalise particles here, see first comment above
}
emitParticles();

```

Reason for this is that you will not time your interval with the main loop which is clearing the screen which prevents you from seeing the 'sparks'

Finally, probably harmless, but to be safe, change the comma to a semi-colon here

```
particlePos.x = ball.x,

```

You can see the above changes working here

# Answer
> 0 votes
I don't see why you are putting it into a separate animation. Why not just have a main game loop and 'inject' the code into the loop? Then you can have a ParticleManager class that can handle the magnitude of created particles, etc.

*I think* the fact that you are putting it in a separate animation *is causing issues*, but is not necessarily the problem.

---
Tags: javascript, html5, html-canvas
---


# Question
Title: Deterministic Multiplayer RTS game questions?
I am working on a cross-platform multiplayer RTS game where the different clients and a server(flash and C#), all need to stay **deterministically synchronised**.

To deal with Floatpoint inconsistencies, I've come across this method: http://joshblog.net/2007/01/30/flash-floating-point-number-errors/#comment-49912 which basically truncates off the nondeterministic part:

```
return Math.round(1000 * float) / 1000;

```

Howewer my concern is that every time there is a division, there is further chance of creating additional floatpoint errors, in essence making it worse?

.

So it occured to me, how about something like this:

```
function floatSafe(number:Number) : Number
{return Math.round(float* 1024) / 1024; }

```
* ie **dividing with only powers of 2** ? What do you think?

.

Ironically with the above method I got less accurate results:

```
trace(  floatSafe(3/5) ) // 0.599609375

```

where as with the other method(dividing with 1000), or just tracing the raw value I am getting **3/5 = 0.6**

or Maybe thats what 3/5 actually is, IE 0.6 cannot really be represented with a floatpoint datatype, and would be more consistent across different platforms?

# Answer
Floating point isn't "non-deterministic". There's no randomness. The floating point value of 1/10 will always be greater than the actual value of 1/10, not just some of the time. The rules are predictable - it's just sometimes hard to know which rules it is using.

Anyway, rounding the value is not guaranteed to work, even if accumulated error wasn't a problem. Any individual error introduced (where error can be defined as a result different from a hypothetical baseline) could make the difference between a value rounding up or a value rounding down, so the rounding operation itself could produce different results on different machines. So basically you eliminate something like 99.9% of your inaccuracies in exchange for getting a much larger inaccuracy 0.1% of the time.

A better idea is to use something truly deterministic, such as fixed point arithmetic, or to set the processor's floating point rules (which may not be possible on your platform).
> 2 votes

# Answer
A value like 0.99900000000000000001 is there because the float cannot represent the original number at all not because the actual operation wasn't correct.

http://steve.hollasch.net/cgindex/coding/ieeefloat.html

That is a the IEEE standard just to give you a reason why rounding wont work. This doesn't mean all CPUs use this format.

I think people serialize their floating point numbers to a standard format over wire and remake the float on the other end, but I'm not entirely sure. You could try doing something like LISP programming langauge and find the value as a "x/y" then send x and y to the client and have him perform "x/y" to get the float.
> 0 votes

---
Tags: multiplayer, rts, floating-point
---