# Question
Title: Why are graphics engines writen in C/C++, when games are GPU bound?
What performance benefits a low level language can give to the engine, when the game is dependent on the GPU?

# Answer
> 1 votes
You cannot generalize that *"games are GPU bound"*. I assume that there are many engines out there for the other case. Otherwise what would we need GPGPU techniques like CUDA or compute shaders for? They outsource computations from the CPU to the GPU.

But speaking for engines for which your statement is correct, there can be several reasons to choose low level programming languages like C or C++.

Games are written in these languages since many years. Therefore you have plenty of game development related libraries available. Moreover, these low level languages are industry standard. Therefore professional developers use them in most of their projects. If a company want to sell a game, there is no time to train the whole team in a new language.

Another reason can be that these developers just prefer these languages because they know them well. Why should a experienced game developer start using Python for his new engine if it is slower and he is already an expert in C++?

# Answer
> 0 votes
Graphic APIs like OpenGL or Direct3d traditionally have APIs which are quite data-driven. They expect to be fed with vertices and textures as arrays of Plain-Old-Data.

A programming language like C (and as an extension C++), which is also very close to the actual representation of the data in memory and doesn't abstract it as much as, for example, Java or Python, have a design philosophy which is much more closer to that of these APIs. As a result, the interface between graphics API and program code usually feels more natural in C/C++. This allows to use them much more efficiently without creating too unreadable code.

---
Tags: c++, gpu
---


# Question
Title: Javascript board game: looking for optimization
### I posted this question on stackoverflow before but received no answers so I decided to post it here and see if someone could suggest me something.

I'm working on a html/javascript game for android. It's a board game which does the following. It has tiles of different colors and user can place one tile (chosen programatically) on the board. If we get 4 or more tiles of the same color/shape we score some points and these tiles will disappear. The tiles above the removed tiles will replace them and new tiles will be added to the empty places. The image below shows how it works **(this is just an example, the real board can have different dimensions)**:

The Tiles are `<img>` elements with their ids stored in an array which I use to check for matches and replacement.

It all works pretty well but once the new tiles are added to board I need to examine the whole board to check if new matches are avalable. And I want some advice here, because examining the whole board can be really slow. Is there a way I can do this efficiently? Here's what I thought about doing:

Given the previous example, I thought about examining only the elements in the red area, i.e. only the elements that have been moved or added. It can be effective if the tiles move vertically, as I'll only have to check the moved/added tiles and it'll give me the new matches. But in case where I remove tiles horizontally it can be problematic, because if these tiles are at the bottom i'll have to examine the whole board and i confront the same problem.

Any advice or suggestion will be appreciated.

Note: I didn't add any code because it simply consists of checking the lines and columns for a given tile and look for matches. But if needed I can provide it.

EDIT: Adding `horizontalMatchCheck` function that for a given index checks for matches horizontally. It's the same thing for vertical check.

```
function horizontalMatchCheck(itemId) {
    hArray = new Array();
    if (rightMatch(itemId)) {
        var index = itemId + 1;
        hArray.push(itemId + 1);
        while (rightMatch(index)) {
            hArray.push(index + 1);
            index++;
        }
    }
    if (leftMatch(itemId)) {
        var index = itemId - 1;
        hArray.push(itemId - 1);
        while (leftMatch(index)) {
            hArray.push(index - 1);
            index--;
        }
    }
    //if >=4 matches found I replace the indexes with 5 (because no other tile can have this id) which'll then be removed and shifted.
    if (hArray.length >= 3) {
        hArray.push(itemId);
        for (var i = 0; i < hArray.length; i++) {
            board[hArray[i]] = items.length;
        }
    }
    else
        hArray = new Array();
}

function rightMatch(pos)
      return (!isRight(pos) && board[(pos+1)] == current) ? 1 : 0 ;
function leftMatch(pos)
      return (!isLeft(pos) && board[(pos-1)] == current) ? 1 : 0 ;

```

# Answer
I admit that I don't exactly understand what your algorithm is for finding matches right now, but I can tell you that there is an easy O(n) method that makes as many passes over the board as directions you want to check in if all you want to check in is straight lines. This is not what you are looking for if you want these matches to include all touching shapes of the same color or shape, this only checks for those that appear in a straight line.

Assuming you have your `board` in a two dimensional array where each shape has a color, shape and a property "isInRun" it is:

```
var shapeRun = [];
var colorRun = [];
for (var i = 0; i < boardX; i++) {
    for (var j = 0; j < boardY; j++) {
        var cell = board[i][j];
        if (i == 0 && j == 0) {
            var currentShape = cell.shape;
            var currentColor = cell.color;
            shapeRun.push(cell);
            colorRun.push(cell);
        } else {
            if (j > 0 && cell.shape == currentShape) {
                shapeRun.push(cell);
            } else {
                if (shapeRun.length >= runLength) {
                    for (var k = 0; k < shapeRun.length; k++) {
                        shapeRun[k].isInRun = true;
                    }
                }
                currentShape = cell.shape;
                shapeRun = [cell];
            }
            if (j > 0 && cell.color == currentColor) {
                colorRun.push(cell);
            } else {
                if (colorRun.length >= runLength) {
                    for (var k = 0; k < colorRun.length; k++) {
                        colorRun[k].isInRun = true;
                    }
                }
                currentColor = cell.color;
                colorRun = [cell];
            }
        }
    }
}

```

This scans each row for "runs" of more than `runLength` shapes and marks them as belonging to a group of matches by setting `isInRun` to true. Do this again but switch

```
var cell = board[i][j];

```

to

```
var cell = board[j][i];

```

To check in the other direction.

Check out this JSFiddle for an example (only tested in Chrome). This creates a random board every 5 seconds with 3 types of shapes and 3 types of colors and then highlights all the matches of 4 or more. You can play around with the parameters at the top of the javascript to change the dimensions of the board or the number of colors and shapes.

I've run this on my phone (a Galaxy Nexus) and I had to bump to board size up to 50x50 to even measure the time it takes.
> 2 votes

# Answer
It looks to me like you're using the DOM as a general-purpose data structure. I would not recommend this approach.

You should separate the game state and rendering, into pieces of logic which are independent of each other. Don't use the DOM as a data store, and don't store references to DOM elements inside your "game state" data.

Having said that, I would also suggest that you consider using a canvas instead of DOM elements. But that's an implementation detail and may not be relevant to your problem.

If you have a simple 2d JS array, with primitive types (integers are good) as elements, it CANNOT be slow to do these lookups, even with a large grid.

In summary:

* Store your board as a 2d array (array-of-arrays). Primitive types (integer) are best, but objects could be ok too.
* Do not keep DOM references inside your game state (if you choose to use DOM elements to render tiles, look them up each time you need them)
> 2 votes

# Answer
This isn't codereview.stackexchange.com, but...

There's no obvious reason for `hArray` to exist. You could just use two local variables, a lower bound and an upper bound, both of which are initialised to `itemId` (which surely should be called `itemIndex`?) and expand them in different directions with simplified versions of the loops.

OTOH this method looks a bit dubious per se. A single scan through the entire row would certainly be quicker than a flood-fill from each cell.

If you really want speed above all else, I believe JavaScript's regex support is quite good...
> 1 votes

---
Tags: android, javascript, optimization
---


# Question
Title: How do I provide a fully programmable pipeline for rendering?
I am writing a game engine and I want people who use it allow to define the rendering pipeline. Just they can define the scene geometry, characters, items, light sources, and so on. So the term programmable pipeline doesn't refer to using custom shaders in OpenGL, which is the case anyway.

To provide a programmable pipeline, I want to abstract the OpenGL level so that people who use the engine don't directly have to struggle with framebuffers, render targets, and so on. The definition of the pipeline have to be done in scripting. The engine will then load the definition and create the framebuffers, render tagets and so on at initialization time.

Are the already approaches to this kind of a programmable pipeline in game engines? How can I let the people who use the engine define the pipeline on a sensible abstraction level? I do not want them to create all their render targets on their own. It would be better to just define connections beweent passes and the shaders which should be used.

Another problem is to connect geometry and lights with the pipeline if it is customizable. How can I approach this challenging goal? Every idea, as answer or comment, is appreciated.

# Answer
> 0 votes
I would recommend looking at as many other engines as you can to see how others have accomplished this task. Creating a general use/universal engine is much more of a challenging task than creating an engine used for smaller one time use projects.

---
Tags: rendering
---


# Question
Title: How to get characters to be aware that their path is obstructed?
I'm using Unity with Arongranberg's A\* pathfinding project to move my characters. However, it appears that my characters are contending for a position on the terrain when they are told to move together to a same position.

For example, I have 5 characters being told to move to `PositionA`. They will move together based on their waypoints to `PositionA`. One of the characters, call it `CharacterA`, will reach `PositionA` before the rest. Now, the other 4 characters who arrived later will continue to keep walking and "sliding" around `CharacterA`. They seem to stop only when `CharacterA` moves away from `PositionA` so that they could reach their destination to break out of the loop. Even so, only one character can be in `PositionA` while the rest will continue to contend for the place.

So, how can I get the characters and objects to know that they have reached their destination and should stop beside the other characters instead of contending for the same place?

A naive method could be I get the characters to detect if they are blocked by something straight ahead of them. If they are, break out of the loop and stop the walking state. But at times when the character hasn't reached his destination yet and is blocked by an object, say another character, breaking out of the waypoint loop will stop him at the wrong destination. I can't recalculate for a new path from his current position either since the blocking object is another character, which the initial pathfinding grid scanning did not take into account. One way is I re-scan the whole terrain for a new grid of nodes with the characters in the scene taken into account. But this wouldn't be efficient and will lag a whole ton.

# Answer
We had a small project with a similar problem.

How we got around this was each character in a group would do their path-finding and save it in a path list. Each node would have a "time" variable for when that character would occupy that node and when creating the next path, the character would make checks against other path lists and consider nodes blocked if the time values would be the same.

This was a bit costly as far as overhead so to counteract this we did not do full path finding just about 5-10 nodes at a time as well as not rebuilding the list until they were almost out of nodes in the path list.
> 1 votes

# Answer
You could try the following: Everytime a character moves, so while he is still walking to his destination, you check, if the destination position is walkable or if it's blocked by something. If it's walkable, everything is fine.

But if it's blocked you calculate the distance between the character and its destination. If it is lower than some certain value, which you can define as you wish, the character knows, that he actually reached his destination, but the position is blocked so he has to stand near the destination. If you define this distance variable well then your characters will just arrange around their shared destination.
> 0 votes

---
Tags: unity, path-finding
---


# Question
Title: Why does this Unity code work as expected only with the while loop?
In unity, in C#, I have the following code in Awake():

```
Awake()
{
    Transform obj = InstantiateTarget();
    //the bizarrely required and "working" loop
    while (transform.childCount > 0)
    {
        //assign all current children to the replacement object
        foreach (Transform t in transform)
        {
            t.parent = obj;
        }
    }

    Destroy(gameObject);
}

```

Without the while loop, some random set of the transforms children are destroyed by that end `Destroy`. With the while, it works exactly as expected (all transform's children become obj's children).

Also, surely with it, there should be an infinite loop (if nothing is changing in another thread, as implied by unity docs). This is in Unity 3.5.

Why does it only work with the while loop? And why doesn't unity get stuck in an infinite loop?

# Answer
> 13 votes
It's actually Unity's fault for being quite confusing here. You are not allowed to alter a collection that you're enumerating with a foreach loop. Suppose this:

```
List<string> SomeList = new List<string>();
//add items to the list
foreach (string s in SomeList)
{
    SomeList.Remove(s); //WRONG! You cannot alter the collection here. Use a for loop instead!
}

```

Normally, this is not allowed in Mono and throws an exception. Unity apparently suppresses it and tells you nothing. Here's what actually happens in your code:

```
Awake()
{
    Transform obj = InstantiateTarget();
    //While there are no children attached to this transform;
    while (transform.childCount > 0) /*Not an infinite loop
                                     because on each step you're removing
                                     a child from this transform
                                     (read on for the explanation).*/
    {
        //Try to attach each child to obj
        foreach (Transform t in transform)
        {
            t.parent = obj; /*The first "t" gets attached, but you're also
                            altering the collection (this.transform loses track of t).
                            The foreach loop stops completely!
                            Since you're executing the foreach loop for
                            as long as this.transfom has children, you
                            essentially remove one child transform at a time on
                            each 'while' pass.*/
        }
    }
    Destroy(gameObject);
}

```

Use a `for` loop instead and, as a rule of thumb, every time you write a `foreach` loop, ask yourself if you're not actually trying to remove items from the collection. If you are, stop right there and use the `for` loop instead.

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


title: Lerp an object based on timers

text:
# Question
Title: Lerp an object based on timers
I'm trying to make a target lerp between two objects based on a timer.

At the moment, I have the following code:

```
   float distCovered = (Time.time - waitTime) * speed;
    float fracJourney = distCovered / journeyLength;
    if (_moveDown == false)
    {
        if (startTime + waitTime < Time.time)
        {

            transform.position = Vector3.Lerp(start.position, end.position, fracJourney);

            if (transform.position == end.position)
            {
                Debug.Log("going down");
               _moveDown = true;

                transform.position = Vector3.Lerp(end.position, start.position, fracJourney);
            }

        }
    }

    if (_moveDown == true)
    {
        float distCovered1 = (Time.time - goDowntimer) * speed;
        float fracJourney1 = distCovered1 / journeyLength;
        transform.position = Vector3.Lerp(end.position, start.position, fracJourney1);

        if (transform.position == start.position)
        {
            Debug.Log("going up");
           // waitTime = 20;
            _moveDown = false;

        }

    }

```

This code is in my update function and is attached to each of my objects that I want to move up and down. Each object is able to set their wait time independently of the others, thus i can have 1 move after 5 seconds, another after 10 etc.

Then, each target waits a few seconds and moves back down. However, the movement isn't smooth and it tends to jump a set distance. But then, when it gets back to the bottom it goes crazy between the \_movedown bool and wont move.

Does anyone know of a way I can fix these issues?

I do know of the Mathf.PingPong method that constantly moves the object back forth between two points, but that wont allow me to pause the movement at each section. Though, if someone knows a way I can do this, please let me know as well.

# Answer
Im assuming this is in unity so I'll suggest based on that. What you should use is the deltaTime to increment your lerp. You can find that in Time.deltaTime and just use that for the third parameter in Lerp. Or if you need to speed it up or slow down you can multiply that delta time by a number you deem the speed.

For the waiting (it looks like you were trying something with waitTime), you just need to decrement the waitTime at the end of your update by deltaTime and do an if(waitTime \<=0) to determine if you can continue to move on.

I didnt really have time to whip up some code for you but if my explanation didnt make sense I can try and get something put together for you =-)

**Edit:** I decided to quickly modify your code. I havent tested this but i think it should work

```
void Update () {
    float distCovered = (Time.time - waitTime) * speed;
    float fracJourney = distCovered / journeyLength;

    if (_moveDown == false)
    {
        if (waitTime <= 0)
        {

            transform.position = Vector3.Lerp(start.position, end.position, Time.deltaTime);

            if (transform.position == end.position)
            {
                Debug.Log("going down");
               _moveDown = true;

                transform.position = Vector3.Lerp(end.position, start.position, fracJourney);
            }

        }
    }

    if (_moveDown == true)
    {
        float distCovered1 = (Time.time - goDowntimer) * speed;
        float fracJourney1 = distCovered1 / journeyLength;
        transform.position = Vector3.Lerp(end.position, start.position, Time.deltaTime);

        if (transform.position == start.position)
        {
            Debug.Log("going up");
            waitTime = 20;
            _moveDown = false;

        }

    }

    if(waitTime > 0)
        waitTime -= Time.deltaTime;

}

```
> 1 votes

---
Tags: c#, unity, interpolation, lerp
---


title: How do I create a 3rd person camera?

text:
# Question
Title: How do I create a 3rd person camera?
I currently have a camera class set up and have my model/player loaded but I can't get my camera in the correct position by changing the x,y,z coordinates.

I have set up my "game" with a separate class for the model/player and a class for the camera. I am fairly new to XNA and most of what I have already got is from a tutorial from my lecturer.

Here is my player/model class:

```
public class Player
{
    public Model model;
    public Matrix world = Matrix.Identity;
    public Vector3 position;
    public Vector3 direction;
    public Quaternion rotation = Quaternion.Identity;
    public BoundingSphere collision;
    public float speed = 2f;
    public float moveForwards;
    public float moveLeft;
    public float forward;
    Matrix[] transform;

    public Player(Model m, Vector3 iPos)
    {
        model = m;
        position = iPos;
        direction = new Vector3(0, 0, 1);
        transform = new Matrix[m.Bones.Count];
        m.CopyAbsoluteBoneTransformsTo(transform);

        foreach (ModelMesh mesh in m.Meshes)
        {
            collision = BoundingSphere.CreateMerged(collision, mesh.BoundingSphere);
        }
    }

    public Player()
    {

    }

    public BoundingSphere getSphere()
    {
        return collision.Transform(world);
    }

    public void sampleInputMovement(GamePadState player)
    {
        moveForwards = (player.ThumbSticks.Left.Y / 5);
        moveLeft = (player.ThumbSticks.Left.X / 32) * -1;
    }

    public void update()
    {
        rotation *= Quaternion.CreateFromAxisAngle(new Vector3(0, 0, -1), moveLeft) * Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), moveForwards);

        Vector3 motion = Vector3.Transform(direction, rotation);
        position += motion * forward;
        world = Matrix.CreateFromQuaternion(rotation) * Matrix.CreateTranslation(position);
    }

    public void Draw(Matrix projection, Matrix view)
    {
        Matrix[] transforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(transforms);

        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.Projection = projection;
                effect.View = view;
                effect.World = transforms[mesh.ParentBone.Index] * world;
            }
            mesh.Draw();
        }
    }
}

```

And here is my camera class:

```
 public class Camera
{
    Vector3 position;
    Vector3 newposition;
    Quaternion cameraRotation;
    Vector3 targetOffset = new Vector3(0, 1f, -6f);

    public Matrix view = Matrix.Identity;
    public Matrix projection = Matrix.Identity;

    public Camera(Game game, Vector3 xPostion)
    {
        position = xPostion;

        projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, game.GraphicsDevice.Viewport.AspectRatio, 1.0f, 1000000f);
    }

    public void update(Matrix targetWorld)
    {
        Quaternion rotation;
        Vector3 target;
        Vector3 scale;

        targetWorld.Decompose(out scale, out rotation, out target);
        cameraRotation = Quaternion.Lerp(cameraRotation, rotation, 0.15f);
        newposition = Vector3.Transform(targetOffset, targetWorld);
        position = Vector3.SmoothStep(position, newposition, 0.8f);

        Vector3 cameraup = Vector3.Transform(new Vector3(0, 1, 0), Matrix.CreateFromQuaternion(cameraRotation));
        view = Matrix.CreateLookAt(position, target, cameraup);
    }
}

```

Could someone help me get my camera in the correct position?

# Answer
When doing a 3rd person camera, simply think about the point in 3d space that the camera is located and the point in 3d space that it is looking at. Set those two points and build a view matrix from them.

```
//I want to locate my camera 25 units behind the player and 5 units above him
Vector3 cameraPosition = targetWorld.Translation + (targetWorld.Backwards * 25) + (targerrWorld.Up * 5);

//I want my cameras to look at a point 10 units directly in front of my player
Vector3 cameraTarget = targetWorld.Translation + (targetWorld.Forward * 10);

//build a view matrix that represents this
view = Matrix.CreateLookAt(cameraPosition, cameraTarget, Vector3.Up);

```

Run this code each frame as `targetWorld` changes and the camera will follow along obediently.
> 1 votes

# Answer
I have managed to get the camera into a 3rd person position by changing the camera offset values but the camera is not at the right hight. When I fix this I will post the fix for that also.

Here is the camera class as it stands:

```
namespace Camera
{
public class Camera
{
    Vector3 position;
    Vector3 newposition;
    Quaternion cameraRotation = Quaternion.Identity;
    Vector3 targetOffset = new Vector3(0, 175f, -100f);

    public Matrix view = Matrix.Identity;
    public Matrix projection = Matrix.Identity;

    public Camera(Game game, Vector3 xPostion)
    {
        position = xPostion;

        projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, game.GraphicsDevice.Viewport.AspectRatio, 1.0f, 1000000f);
    }

    public void update(Matrix targetWorld)
    {
        Quaternion rotation;
        Vector3 target;
        Vector3 scale;

        targetWorld.Decompose(out scale, out rotation, out target);
        cameraRotation = Quaternion.Lerp(cameraRotation, rotation, 0.15f);
        newposition = Vector3.Transform(targetOffset, targetWorld);
        position = Vector3.SmoothStep(position, newposition, 0.8f);

        Vector3 cameraup = Vector3.Transform(new Vector3(0, 1, 0), Matrix.CreateFromQuaternion(cameraRotation));
        view = Matrix.CreateLookAt(position, target, cameraup);
    }
}
}

```
> -1 votes

# Answer
Thanks to Steve H we have managed to get it working.

Here is the camera class with the correct height as well as placement behind my model.

```
class Camera
{
    public Matrix view = Matrix.Identity;
    public Matrix projection = Matrix.Identity;
    public Matrix world = Matrix.Identity;
    public BoundingSphere collision;

    public Camera(Game game)
    {
        projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, game.GraphicsDevice.Viewport.AspectRatio, 1.0f, 1000000f);

    }

    public BoundingSphere getSphere()
    {
        return collision.Transform(world);
    }

    public void update(Matrix targetWorld)
    {
        Vector3 position = targetWorld.Translation + (targetWorld.Forward * 110) + (Vector3.Up * 100);

        Vector3 target = targetWorld.Translation + (targetWorld.Backward * 10) + (Vector3.Up * 80);

        view = Matrix.CreateLookAt(position, target, Vector3.Up);
    }
}

```
> -1 votes

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


# Question
Title: Why no night sky with realistic star constellations?
As an amateur stargazer I noticed that many games which have night scenarios use textures for the night sky where the stars seem to be arranged entirely randomly. It seems like they were created by an artist from scratch without looking at a star chart. Why don't they use a night sky texture where the stars are arranged like on the real night sky, so you can make out well-known constellations?

Games which take place in a fantasy or science fiction scenario are obviously excused, but why do games which take place on earth spend so much work on realism, but neglect this one aspect, even though there are plenty of public domain resources which could be used to create a realistic night sky?

# Answer
All the current answers are very good, but I want to propose a different point of view.

Even though I would say the vast majority of games don't get their stars right is out of straight laziness and/or ignorance. The same goes for firearm sounds, physics (ever played a racing game? any racing game?), history (for historical games) and many other fields.

However, if I were directing a game, I may not aim for realism in certain elements such as the star field, and I would do so *intentionally*, on aspects that are not crucial to gameplay.

The reason behind this is that the more you aim for realism, the larger the player expectations will be on that realism. And while player expectations have no limit, budget and time do.

So suppose I got a star chart for my game, and I use that as my skybox. Players who notice that, will then criticize that the stars are 3 degrees off, or that based on the vegetation you see in the game, you can estimate the latitude where the game is taking place, and that the star field doesn't correspond to such a latitude.

So even if I fix that, more players would then criticize that you can't see the ISS, or that some star has an apparent magnitude of 4.5, but in the game it looks like 4.8.

Rinse and repeat.

The point here is that, the more you aim for realism, the bigger your players' expectations will be. If your game requires realism in some aspect, then by all means dedicate your time and money to maximizing this realism. For all the rest, I would probably intentionally make it unrealistic, so I can keep my focus and that of my players in the parts of the game that actually matter.
> 15 votes

# Answer
Your question is based on the false assumption that most games are realistic. This is not the case, even if games take place in a familiar setting. Consider, for example, health regeneration in modern shooters.

Game developers that "spend so much work on realism" and aim for realism as a selling point are actually quite rare and are usually found in niche genres like aircraft or military sims.

An example is the Arma series games, based on VBS, which does have realistic star constellations (and basically everything else):

> VBS2 is highly accurate in its rendering of seasonal patterns. Thus daylight hours, the sun's path across the sky, star constellations and moon phases are all simulated correctly given the current terrain's world location. Tides are also accurately simulated, and can be somewhat hard to predict as different seasons and moon phases create vastly differing high/low water marks.

(source)

VBS has these features because they are relevant to its users. For example, to train soldiers to navigate by starlight.

Another example is Microsoft Flight Simulator X:

> Improved graphics including enhanced texture resolution, new Earth model facilitating polar flights, true road data, region-specific textures, minimal 3D animals, star constellations, etc.

(source)

In short: most games are not accurate simulations of real-life. And if a feature costs money (and they all do) and does not add value (except to a handful of *star gazers/gun nuts/medical professionals*) it won't make the cut. This is why you won't see a lot of realistic *nightskies/weapon reloading/gunshot wound treatment* in games.
> 39 votes

# Answer
I'd just say memory restrictions: It's far easier to use a relatively small texture (either due to hardware restrictions or for performance reasons) and just repeat it over and over again instead of mapping the whole sky "as is" as long as it's no core gameplay element (and just decoration). This has been even more noticeable in old games, e.g. on consoles from the 80's or 90's where you usually had a very simple pattern (if any at all; i.e. 1-2 stars per tile only).

From time to time devs still tend to include some well known constellations just for people to notice them.

Two examples coming to my mind, first one being **Illusion of Gaia** (known as **Illusion of Time** in Europe), where the Cygnus constellation played a major role in the plot (the red "star" is meant to be a new star that appeared heralding things to come):

Another example would be **Mega Man 2**. There's one stage featuring stars in the background. They've added a very easily noticeable Ursa Major right before the end of the Crash Man stage:
> 23 votes

# Answer
Good question!

Reason number one: Laziness. It's much easier to just hit random noise on a texture and be done with it.

Reason number two: Artistic direction. Have you noticed how ludicrous the moon is on the night sky in the games that have it?

Reason number three: resources. Once you start to strive for realism in the night sky, you want a very, very high-resolution texture to pull it off. Having a lower-resolution texture, or using tiling tricks to get a higher resolution, makes it harder for the "realistic night sky" to look good while looking "right".
> 15 votes

# Answer
The simple answer is that to do a realistic night sky including constellations, you either need to use a lot of texture resolution, or a lot of geometry. Or both.

Most modern games want to spend their texture budget and rendering draw calls on things which impact directly on the play experience, which they know that every player is going to be focusing on for most of the time. Which means that the only games which typically spend a lot of time representing stars and constellations accurately are detailed space sims, where they can be important for navigation. (I expect that you'd see them in sailing sims, too, for the same reason)
> 8 votes

# Answer
You are talking about a different kind of realism here. When referring to games, "realism" usually means that when an object appears it looks like it's actually there. (Or given it's on a flat screen, perhaps a photograph is a better analogy?) The effect is usually obtained via high resolution textures and so on.

The realism you are referring to, however, is that an object *exactly* represents the corresponding real-world object. So if you have a brick wall with some mold on, by your definition it must only appear in exactly the way mold grows in real life. Or if the game is set in New York, every shop must be exactly what is in the real city, and every trash can and subway entrance must be in exactly the correct place.

As I'm sure you can understand, it's incredibly difficult to make every single detail like this accurate. Games just take a "good enough" approach. How many users are ever going to know that the stars are not correct? However, the sky *is* realistic by the usual definition, in the sense it looks like real stars and are not pink blobs in the sky.
> 1 votes

# Answer
One good reason is that most gamers don't go outdoors much. To check that the star display in a game is indeed authentic, they will probably Google it, ironically. So this is a waste of effort. It's also pointless in any game which portrays an imaginary world, only making sense in games or simulations which have real settings.

The focus in modern game graphics is realism, rather than authenticity, because realism is what enhances the sense of immersion into the game's world, whereas authenticity is more of an intellectual aspect.
> -7 votes

---
Tags: graphics, graphics-design, sky
---


# Question
Title: Simple game engines / development tools made with artists in mind?
I've been working in the 2d art side of games for a while now, and my full time job keeps me very busy on the art side of things, but I'm becoming more and more interested in learning to prototype my own games.

I know very very little programming, though I did take some in college (in TorqueScript, of all things), and while I could probably take the time to learn it, the learning curve is a bit too steep for me as it's completely separated from my current job.

I'm wondering if there are any game engines out there with an interface designed with artists in mind, where the learning curve might be easier for me, and where my current skill set will be more easily applied. I bought an indy license for Torque Game Builder but it still requires a lot of scripting and finding good, basic, entry-level tutorials is proving difficult.

Basically I'm looking for a tool where I can focus on the art and game design, and where the programming is minimal, or is easy to learn and has really excellent documentation. No idea if anything like that exists, but it's worth a shot. :\]

Any ideas?

# Answer
My recommendation would be to check out Unity, as it is one of the simplest, yet deceptively powerful, engines I have run across. The engine is well documented, the community is very active and friendly, and there are a number of tutorials available to help you get up to speed.

**Update:** Although Unity has a bit of a learning curve, I chose to recommend it over other engines for a couple of reasons:

* **Workflow** \- Unlike simpler engines out there, Unity uses a workflow that is similar in many aspects to what is used in the game industry, meaning that your time spent learning is an investment toward your career, not just learning a tool.
* **Support** \- Unity has a very active and friendly community, which is something a lot of smaller engines don't have.
* **Power** \- Unity comes with a lot of features and supports a number of platforms.
> 16 votes

# Answer
I think you would do well choosing one of the many game making tools. There's little to no programming involved. Some even offer graphical, drag & drop programming interfaces.
> 12 votes

# Answer
The Blender Game Engine might also be worth a look. It is part of the free 3d animation and modelling software Blender. It doesn't require any programming skills to create something but is also extendable by using python scripting. This probably only makes sense if you're using blender for asset creation anyway though.
> 6 votes

# Answer
Take a look at Scratch: http://scratch.mit.edu It's a free tool designed for kids by MIT, but it might be exactly what you're looking for. All the programming is done with tiles, so you don't need to learn any syntax. You can import your own graphics and audio, and the scripting is going to be relatively easy (I've taught 9-year-olds to make decent games in two hours.)

-um, and it's free, so there's really not a good reason NOT to try it.
> 6 votes

# Answer
Definitely look at Flash. http://flashgamedojo.com has all you need to get started!

Also, take a look at Multimedia Fusion or The Games Factory. They both have drag and drop interfaces, but they're incredibly powerful.
> 6 votes

# Answer
For 2D rapid-prototyping, I would suggest Game Maker. It allows a designer to quickly import art assets and turn them into animated sprites, and feature a simple object system which is event based. You can prototype simple games using drag and drop.

Another one I would recommend is Multimedia Fusion. It takes a different approach to programming in which it uses a big event table to handle interactions between objects. There are some simple scripting too.
> 5 votes

# Answer
i wonder why no one said anything about FREEWARE AND OPEN-SOURCE Constructor game engine. its mostly also drag-and-drop, has a solid suppport and is easy to learn and use. you dont need to know any programing knowledge beside plain variables and conditions. ty it out http://www.scirra.com
> 2 votes

# Answer
For 2D, I think Game Maker is good.

For 3D, I think 3DVIA is the better choice because you can script the engine with a graph.

Unity is very good but you'll have to learn a bit of programming to make it shine.
> 1 votes

# Answer
I'd suggest you check out UDK (the free-to-download Unreal engine and tools). There instead of having to write script, they have a system called Kismet which allows you to 'script' a lot of the typical gameplay events using a drag-drop system. What's more, there's a whole video tutorial series recorded by the good people at 3DBuzz. Ofc it's a 3d engine which might not suit, but there are tutorials on how to create a top-down game with it.

The trouble with most of the other suggestions here is that while they are good systems, they still require you to learn a programming language and if you found TorqueScript too much of a learning curve then I doubt Python (as used by Blender) or some of the other options are going to be any easier (although they are better documented than TorqueScript - everything is better documented than Torquescript :) )
> 1 votes

# Answer
I know you've already marked an answer on this, but just another thought to throw out there: If you have a solid portfolio of art & game design, finding a programmer to help you prototype out some stuff and maybe even make a full game would be a good way to prototype without having to code yourself. Its not exactly a tool persay, but depending on your intent it might be the most effective way.

Obviously with a tool you don't have to worry about depending on or motivating someone else. However it can also release you from having to fight the beast that is code even in something like Unity, letting you handle the creative side with all your effort.

I know as a programmer with the opposite problem, ie looking for ways to make art with minimal effort, I have found working with an artist to be a much more delightful experience than working both disciplines myself and trying to do art through the most minimal tools. ;)
> 1 votes

# Answer
If you really want to start game development, I think I can share you the starting point I did. First off, I did learn Basic Java Programming, Intermediate and Game Dev by thenewboston (seach this username in Youtube), you can learn many things from him. But before that, I used the game engine RPG Maker XP, VX and VXAce. They are great engines to make small or big rpg games.

You can also check FPS Creator, if you like FPS. But I'd say coding the game yourself is better of an enjoyment than using these...
> 1 votes

# Answer
FlashPunk is a very well documented and easy to use framework for Flash. As someone with a background in design I was able to pick up the code very quickly, and it handles a lot of the things that new programmers get hung up on automatically.

http://flashpunk.net/
> 1 votes

# Answer
UDK by Epic Games will be the best choice for you;) It has a lot of stuff for artists and you can program on UnrealScript. As I understand UnrealScript's library is mirror of native C++ code. So you'll find some interesting tricks in programming of hierarchy structures, animation, triggers and etc. You can see and control pipeline of your gameplay and art. And of course the programming can be minimal. Because you can "draw" your game with embedded script editor "Unreal Kismet". There are a lot of video tutorials. Enjoy!

**Update:** I must say that UDK works "from the box". I think it is very good reason to choose;)
> 0 votes

# Answer
All of the other answers are OK, but I'd also suggest you take a look at HTML5. Yes, I know, that isn't exactly a game engine, but it's really simple and has a fast growing community. All you need is a canvas element somewhere on the page, and then you use Javascript to draw on it. I'd go with this rather than with Scratch or Game Maker, because it will actually teach you some usefull programming skills.

There are a number of good tutorials out there, but first learn basic HTML, then some Javascript, and then go here.
> 0 votes

# Answer
come and take a look at App Game Kit. We've been developing it since 2009 and it's great at 2D spites games. It has box 2D built in too.

You can code in BASIC or use the libraries from C++.

www.appgamekit.com

Just the other day someone posted this great Defender remake which he coded in the BASIC script; http://youtu.be/l50amgFImKc

Cheers,

Rick
> 0 votes

---
Tags: software-engineering, art
---


title: Creating physics in xna

text:
# Question
Title: Creating physics in xna
I am creating a racing game using visual studio 2010 and xna 4.0. I'm trying to create some simple physics so my car sticks to the heightmap I have created within my game world and the model adjusts its height and pitch accordingly. I have added some code that should in theory do just this but my model doesn't adjust to the heightmap and just phases through the taller sections. Would anyone be able to help me out/point me in the right direction?

Here is the class I have been working on, I know it is a lot of code to look through and I apologise in advance but I really can't work out why my model isn't responding as it should. Any help is greatly appreciated.

```
namespace Turbo_Rally
{
class Heightmap
{
    float[,] heightData;
    Vector3[,] normals;
    public int terrainWidth;
    public int terrainHeight;
    public Vector3 heightmapPosition;
    float terrainScale = 400f;
    float verticalScale = 30f;
    VertexPositionNormalTexture[] vertices;
    int[] faces;

    BasicEffect effect;
    Texture2D texture;
    GraphicsDevice graphics;
    Matrix world;

    public Heightmap(GraphicsDevice gd, Texture2D terrainTexture, Texture2D heightmap)
    {
        graphics = gd;
        texture = terrainTexture;
        terrainWidth = heightmap.Width;
        terrainHeight = heightmap.Height;
        faces = new int[(terrainWidth - 1) * (terrainHeight - 1) * 6];
        vertices = new VertexPositionNormalTexture[terrainWidth * terrainHeight];
        effect = new BasicEffect(graphics);

        buildHeightmap(heightmap);
        heightmapPosition.X = 0;
        heightmapPosition.Y = 0;

        for (int z = 0; z < terrainHeight; z++)
        {
            for (int x = 0; x < terrainWidth; x++)
            {
                vertices[x + z * terrainWidth].Position.X = terrainScale * (x);
                vertices[x + z * terrainWidth].Position.Z = terrainScale * (z);
                vertices[x + z * terrainWidth].Position.Y = heightData[x, z];
                vertices[x + z * terrainWidth].Normal = Vector3.Zero;
                vertices[x + z * terrainWidth].TextureCoordinate.X = (float)x / terrainWidth;
                vertices[x + z * terrainWidth].TextureCoordinate.Y = (float)z / terrainHeight;
            }
        }

        int count = 0;
        for (int z = 0; z < terrainHeight - 1; z++)
        {
            for (int x = 0; x < terrainWidth - 1; x++)
            {
                int lowerLeft = x + z * terrainWidth;
                int lowerRight = (x + 1) + z * terrainWidth;
                int topLeft = x + (z + 1) * terrainWidth;
                int topRight = (x + 1) + (z + 1) * terrainWidth;

                faces[count++] = topLeft;
                faces[count++] = lowerRight;
                faces[count++] = lowerLeft;
                faces[count++] = topLeft;
                faces[count++] = topRight;
                faces[count++] = lowerRight;
            }
        }
    }

    public bool BoundingTest(Vector3 position)
    {
        if (position.X > 0 && position.X < (heightData.GetLength(0) - 1) * terrainScale && position.Z > 0 && position.Z < (heightData.GetLength(1) - 1) * terrainScale)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public float GetHeight(Vector3 position)
    {
        //Determining the cell the player is positioned in
        int left, top;
        left = (int)position.X / (int)terrainScale;
        top = (int)position.Z / (int)terrainScale;

        //Working out our position within the cell
        float xNormalized = (position.X % terrainScale) / terrainScale;
        float zNormalized = (position.Z % terrainScale) / terrainScale;

        //Calculating height
        float topHeight = MathHelper.Lerp(heightData[left, top],
                        heightData[left + 1, top],
                        xNormalized);

        float bottomHeight = MathHelper.Lerp(heightData[left, top + 1],
                        heightData[left + 1, top + 1],
                        xNormalized);

        //Finding exact height
        return MathHelper.Lerp(topHeight, bottomHeight, zNormalized);
    }

    public void buildHeightmap(Texture2D heightMap)
    {
        Color[] heightmapColors = new Color[terrainWidth * terrainHeight];
        heightMap.GetData(heightmapColors);

        heightData = new float[terrainWidth, terrainHeight];
        for (int x = 0; x < terrainWidth; x++)
            for (int y = 0; y < terrainHeight; y++)
            {
                heightData[x, y] = heightmapColors[x + y * terrainWidth].R * verticalScale;
            }
    }

    public void calculateNormals()
    {
        for (int i = 0; i < faces.Length / 3; i++)
        {
            Vector3 firstvec = vertices[faces[i * 3 + 1]].Position - vertices[faces[i * 3]].Position;
            Vector3 secondvec = vertices[faces[i * 3]].Position - vertices[faces[i * 3 + 2]].Position;
            Vector3 normal = Vector3.Cross(firstvec, secondvec);
            normal.Normalize();
            vertices[faces[i * 3]].Normal += normal;
            vertices[faces[i * 3 + 1]].Normal += normal;
            vertices[faces[i * 3 + 2]].Normal += normal;
        }

        normals = new Vector3[terrainWidth, terrainHeight];
        for (int x = 0; x < terrainWidth; x++)
        {
            for (int z = 0; z < terrainHeight; z++)
            {
                normals[x, z] = vertices[x + z * terrainWidth].Normal;
            }
        }
    }

    public Vector3 GetNormal(Vector3 position)
    {
        int left, top;
        left = (int)position.X / (int)terrainScale;
        top = (int)position.Z / (int)terrainScale;

        float xNormalized = (position.X % terrainScale) / terrainScale;
        float zNormalized = (position.Z % terrainScale) / terrainScale;

        Vector3 topNormal = Vector3.Lerp(normals[left, top],
                      normals[left + 1, top],
                      xNormalized);

        Vector3 bottomNormal = Vector3.Lerp(normals[left, top + 1],
                      normals[left + 1, top + 1],
                      xNormalized);

        Vector3 normal = Vector3.Lerp(topNormal, bottomNormal, zNormalized);
        normal.Normalize();
        return (normal);
    }

    public void Draw(Matrix projection, Matrix view)
    {
        effect.Texture = texture;
        effect.TextureEnabled = true;
        effect.EnableDefaultLighting();
        effect.DirectionalLight0.Direction = new Vector3(1, -1, 1);
        effect.DirectionalLight0.Enabled = true;
        effect.DirectionalLight1.Enabled = false;
        effect.DirectionalLight2.Enabled = false;
        effect.AmbientLightColor = new Vector3(0.8f, 0.8f, 0.8f);
        effect.SpecularColor = new Vector3(0, 0, 0);
        effect.Projection = projection;
        effect.World = Matrix.Identity;
        effect.View = view;

        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();
            {
                graphics.DrawUserIndexedPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList, vertices, 0, vertices.Length, faces, 0, faces.Length / 3);
            }
        }

        RasterizerState rs = new RasterizerState();
        rs.FillMode = FillMode.Solid;
        rs.CullMode = CullMode.None;
        graphics.RasterizerState = rs;
    }
}
}

```

# Answer
> 1 votes
Looks like you are forgetting to multiply the final Lerp in GetHeight by the terrainHeight.

Also, based on the comments below, you need to add the following:

in your Update() method for your player model after changing the pos vector:

```
effect.World = Matrix.CreateTranslation(pos.x, GetHeight(pos), pos.z);

```

where effect is the Effect that you are using to render the player model and pos is a Vector3 that you are using to store the player models position. Obviously change the names if they are different in your routine.

At this point I would actually recommend that you do a little more reading up about how 3d graphics are created, managed and rendered in xna, specifically the Matrix class. The information I have tried to help you with is fairly basic stuff and if you dont fully understand it then you will have countless problems going forward.

---
Tags: xna, c#, physics, heightmap
---


# Question
Title: How to clear a buffer to 1.0 instead of 0.0 in OpenGL?
Using `glClear()` you can set the buffer specified by the parameter to `0.0`. This is useful say if you want pixels not covered by models to be black. Because `vec3(0.0, 0.0, 0.0)` results in black.

But for the depth buffer, clearing means to set it to the maximum value `1.0` since you don't want pixels not covered by models to have the depth `0.0` which is the camera's position but to have the depth `1.0` which means as far away as possible.

So how can I clear the depth buffer to `1.0` or come over this issue in another way?

# Answer
> 7 votes
You use:

* `glClearColor(r, g, b, a)` to set the color of `glClear(GL_COLOR_BUFFER_BIT)`
* `glClearDepth(depth)` for the depth buffer
* `glClearStencil(stencil)` for the stencil buffer

Alternatively, you can use `glDepthFunc` to change the way the depth buffer is tested.

# Answer
> 5 votes
You can use the function `glClearDepth` where you can specify what to clear the depth buffer to. http://www.opengl.org/sdk/docs/man/xhtml/glClearDepth.xml however I think `glClear()` clears the depth buffer to 1.0 by default.

> glClear sets the bitplane area of the window to values previously selected by glClearColor, glClearDepth, and glClearStencil

As `glClearDepth` states

> Specifies the depth value used when the depth buffer is cleared. The initial value is 1.

---
Tags: opengl, depth-buffer
---


title: Wander algorithm for a maze

text:
# Question
Title: Wander algorithm for a maze
I am making a multiplayer coop FPS game. I have created the first monster with it's AI. I have worked out the A\* algorithm for the level based on the triangles of the walkable mesh. So I can already find a path from point A to point B in the level. The question is, how would I implement a random wander algorithm?

The simple wander and evade obstacle steering behavior will not do, I think. I probably need to use the Path finding data.

What kind of algorithm do you suggest?

# Answer
> 3 votes
The easiest way to do this seems to be to simply generate a random point on the mesh and walk to it. You can restrict the point to be within a radius of the monster's position in order to avoid really long random walks too.

---
Tags: 3d, ai, path-finding, steering-behaviors
---


# Question
Title: Projectile immediately intersecting with target
I have a fairly simple and somewhat cookie cutter method for `testCollisions:` (FYI: BasicProjectile is a CCNode with a CCSprite member).

```
    for (BasicProjectile * basicProjectile in self.projectiles) {

        NSLog(@"projectile sprite %@",NSStringFromCGRect(basicProjectile.sprite.boundingBox));
        NSLog(@"destination sprite %@",NSStringFromCGRect(basicProjectile.destination.sprite.boundingBox));

            if (CGRectIntersectsRect(basicProjectile.sprite.boundingBox, basicProjectile.destination.sprite.boundingBox)) {

                [basicProjectile.destination setHealth:(basicProjectile.destination.hp - basicProjectile.damage)];

                [self.projectiles removeObject:basicProjectile];
                [self removeChild:basicProjectile cleanup:YES];
                }
        }

    }

```

Those NSLog statements output:

> 2013-03-23 10:02:59.124 GridWars\[25268:c07\] projectile sprite {{-10, -10}, {20, 20}}
>
> 2013-03-23 10:02:59.124 GridWars\[25268:c07\] destination sprite {{-13.5, -34}, {27, 68}}

The main problem is that the collision immediately happens. It should take a few frames to travel from the source to the destination. So although the logic of setting the health works fine the sprite itself is never seen on the screen because the very second its fired it is removed.
From what I understand about `CGRectIntersectsRect` those 2 points listed above do not intersect. Am I wrong are they intersecting? What can be causing these projectiles to immediately intersect with their target?

BasicProjectile class (CCNODE superclass)

```
-(id)initWithSourceAndDestination:(GameCharacters*)Source destination:(GameCharacters*)Destination
{
    if (self = [super init]) {
        self.damage = 25;
        self.sprite = [CCSprite spriteWithFile:@"Projectile.png"];
        [self addChild:self.sprite z:1000 ];
        self.source = Source;
        self.destination = Destination;
    }
    return self;
}

```

GameCharacters would look similar to this except have health and mana properties.

WizardHero Class, Method Fire:

basicProjectile.position = self.position; \[self.hostLayer addChild:basicProjectile z:2021\];

```
// Determine where we wish to shoot the projectile to
int realX;

// Are we shooting to the left or right?
CGPoint diff = ccpSub(basicProjectile.destination.position, basicProjectile.source.position);
if (diff.x > 0)
{
    realX = (self.hostLayer.tileMap.mapSize.width * self.hostLayer.tileMap.tileSize.width) +
    (basicProjectile.contentSize.width/2);
} else {
    realX = -(self.hostLayer.tileMap.mapSize.width * self.hostLayer.tileMap.tileSize.width) -
    (basicProjectile.contentSize.width/2);
}
float ratio = (float) diff.y / (float) diff.x;
int realY = ((realX - basicProjectile.position.x) * ratio) + basicProjectile.position.y;
CGPoint realDest = ccp(realX, realY);

// Determine the length of how far we're shooting
int offRealX = realX - basicProjectile.position.x;
int offRealY = realY - basicProjectile.position.y;
float length = sqrtf((offRealX*offRealX) + (offRealY*offRealY));
float velocity = 380/1; // 380pixels/1sec
float realMoveDuration = length/velocity;

// Move projectile to actual endpoint
id actionMoveDone = [CCCallFuncN actionWithTarget:self.hostLayer
                                         selector:@selector(projectileMoveFinished:)];
[basicProjectile runAction:
 [CCSequence actionOne:
  [CCMoveTo actionWithDuration: realMoveDuration
                      position: realDest]
                   two: actionMoveDone]];

[self.hostLayer.projectiles addObject:basicProjectile];

```

Basically here is the class structure

Three main superclasses

> GameProjectiles:CCNodes
>
> GameLevels:CCNodes
>
> GameChars:CCNodes

Then the actual more specific classes (used on the GameLevels)

> BasicProjectile:GameProjectiles
>
> Level1Layer:GameLevels
>
> WizardHero:GameCharacters
>
> RedEnemy:GameCharacters

# Answer
> 0 votes
(copied from my other question https://stackoverflow.com/a/15686025/530933)

since your projectiles and targets are inside a separate CCNode, their bounding box returns their position inside their parent and not in actual screen coordinates (which you want in your case).

To convert the pos you can do like this

```
CGPoint targetPos = [basicProjectile.destination.sprite.parent convertToWorldSpace:basicProjectile.destination.sprite.position];
NSLog(@"targetPos  %@",NSStringFromCGPoint(targetPos));
CGRect targetRect = [self boundingRectForSprite:basicProjectile.destination.sprite andPos:targetPos];

CGPoint projectilePos = [basicProjectile.sprite.parent convertToWorldSpace:basicProjectile.sprite.position];
NSLog(@"projectilePos  %@",NSStringFromCGPoint(projectilePos));
CGRect projectileRect = [self boundingRectForSprite:basicProjectile.destination.sprite andPos:projectilePos];

```

the boundingRectForSprite method makes the uses the sprite bounding box and position and then calculates the final rect taking anchor point of (0.5,0.5).

now the targetRect and projectileRect are of actual screen coordinates.

---
Tags: cocos2d-iphone
---


title: Android bitmap placing

text:
# Question
Title: Android bitmap placing
I've recently added an explosion in my game, for when enemies get killed, and it works fine and all, but the explosion wont "spawn" on the enemies `x` and `y`. The problem is that I'm not drawing the bitmap from the center, but from its `0,0` position, so the explosion spawns at my enemies `0,0`. It's not like the explosion spawns at random places, it spawns around the enemies bitmap, but just not on the center, and it is really annoying to look at.

But if I try to change it so I add them at the center, It creates a really weird effect when rotating them that is hard to explain.

I cant use this: `canvas.drawBitmap(bitmap, x - bitmap.getWidth/2, y - bitmap.getHeight/2, null);`, or I'm just doing it wrong and missing something.

How I draw my enemies:

```
    public void draw(Canvas canvas) {
    canvas.save();
    canvas.rotate((float) rotater, x + (width / 2), y + (height/2));
    int srcX = currentFrame * width;
    int srcY = 0 * height;
    Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
    Rect dst = new Rect(x, y, x + width, y + height);
    canvas.drawBitmap(bitmap, src, dst, null);
    canvas.restore();
}

```

How I add my explosions:

```
    if (enemies.get(i).getHP() <= 0) {  //enemy death
        addExplosion(enemies.get(i).getX(), enemies.get(i).getY());

```

If you need any more info to be able to help, let me know. Thank you!

# Answer
Try something like this (this is pseudocode, I don't know your objects actual fields)

1 - determine the enemy's center.

```
centerX = enemy.getX() + (enemy.getWidth() /2 );
centerY = enemy.getY() + (enemy.getHeight() / 2);

```

2 - assume the center of the explosion is the same center of the enemy and determine that explosion top-left from its size

```
explosion.setX(centerX - (explosion.getWidth() / 2);
explosion.setY(centerY - (explosion.getHeight() / 2);

```
> 2 votes

# Answer
When you add an explosion, your enemy object should return its center like this: addExplosion(enemies.get(i).getCenterX(), enemies.get(i).getCenterY());

The drawing of an explosion should happen after canvas.restore(); so that is not affected by the enemie's rotation. Every object drawn on Canvas can have its own canvas.save()/cavas.transform/canvas.restore() especially when the rotational pivotal point is not the same for all objects.

Do not create new objects in onDraw, such as new Rect. You can use the same ones with **src.set(0,0,0,0);**

For each group of objects create a draw method, and in onDraw just call them one by one and pass the canvas. i.e. drawEnemyShips(canvas); drawExplostions(canvas);
> 0 votes

---
Tags: java, android
---


# Question
Title: GLSL Editor and Debugger for MacOSX with ES2 support
is there a GLSL editor for the mac? I need it for iOS OpenGLES2 shader.

How do you best debug shader?

Regards

# Answer
There are two supported GLSL editors for OS X. The first, known as Shader Builder, comes with the Graphics Tools available from the Apple developer website. The second is the open source Shader Maker. Neither of these tools are strictly for OpenGL ES 2.0, but the best workflow would probably be to get the look you want before you determine how to get the look you can have.

In terms of debugging shaders, it is very difficult to send debugging information back to the CPU. The only strategy that I have ever used is to use conditionals to output a specific color to the screen and look at the output. Tools such as glslDevil also exist, but not for OS X.
> 5 votes

---
Tags: shaders, ios, tools, glsl, macos
---


# Question
Title: 100 points between 0-1000 on an increasing scale
Basically, it's for roleplay, I need to generate 100 points along a scale. Level 1 is the starting amount, and is at point 0 on the scale. Level 100 is the highest amount planned at this point, and it needs to be at 1,000 on the scale.

My problem is generating points 2-99 between those two. I could do it cheaply and just go with one level at every 10 points. But that's not how I want it to function.

Ideally, I'd like a sloping curve, so that in the early stages, levels might be only a number or two apart. Such as:

Level 1 - 0
Level 2 - 2
Level 3 - 4

But then as the level increases, the number also goes up.

Level 98 - 960
Level 99 - 980
Level 100 - 1000

Can someone help me figure this out?

# Answer
One way to do this is with a power curve, where you choose the power and then scale it to give the right value at the max level:

```
points = pow(level, somePower) * (maxPoints / pow(maxLevel, somePower))

```

For example, if you choose `somePower = 1.5` then you get

```
level 0 = 0.000000 points
level 1 = 1.000000 points
level 2 = 2.828427 points
level 98 = 970.150504 points
level 99 = 985.037563 points
level 100 = 1000.000000 points

```

Presumably you'd round the points to the nearest integer, and tweak `somePower` to get the curve you want. Higher powers will make the curve slower at the start and faster at the end.

Edit: at Byte56's suggestion, I added a picture from Wolfram Alpha. :)
> 11 votes

# Answer
If you're intending to use only integers then I would give serious consideration to expanding the range from 1000 to something higher; an average of ten units between levels means that you'll either be too cramped to differentiate at the low end, or too close between levels at the high end. For instance, one fairly common way of spacing levels is to use *quadratic* growth: make the 'point count' of level n proportional to n2. This means that the gap between levels grows linearly: the number of points needed to go from level n to level (n+1) is (roughly) proportional to n. Unfortunately, if we try and fit this approach to your data, then to get level 100 at 1000 points, we need to take the constant of proportionality to be (1002) / 1000, or 1/10; in other words, the number of points needed for level n is n2/10. This works well at the high end: level 100 is at 1000 points, level 99 is at (992)/10 = 980 points, level 98 is at 960 points, level 97 is at 940.9 = 941 points, etc. Unfortunately, on the low end this means that the number of points for level 1 is 0, but the number of points for level 2 is (22)/10 = 0.4 = 0 also, then level 3 is at 1, level 4 is at 2, etc.

Another approach used is to go for exponential growth, where each level is some constant times the size of the previous. Unfortunately, over 100 levels this runs into similar and arguably even worse problems - to grow from 1 to 1000 over that span you'd need to multiply each number by 1000(1/100) = 1.0715, or 7% growth from level to level - this means that level 1 is at 1, level 2 is at 1.07 = 1, level 3 is at 1.15 = 1, ..., up to level 97=813 points, level 98=871 points, level 99=933 points, level 100 = 1000 points. This approach works better with a much smaller number of levels - for instance, over a span of roughly 20 or so levels.

If you have to go from 0 to 1000, then I would consider a hybrid approach; have the first few levels' growth be explicitly linear, then switch over to a quadratic growth rate somewhere around level 10 or so. You should be able to tune your parameter values so there's decent separation at both ends of the scale.
> 2 votes

---
Tags: game-design, mathematics, algorithm
---


# Question
Title: Player positions in a race game through arrays or...?
First time posting on these forums so go easy on me!

I've been programming a race game which has been going quite well. I've just discovered now how hard it is to set up player positions!(As in 1st, 2nd, 3rd, etc). From research I've discovered that the easiest way of doing this is through checkpoints which I've successfully managed to set up. Each player races through the checkpoints in the game and this progress is stored as an int. There's 2 int, one for laps and one for checkpoints. When the checkpoint integer reaches a certain number it resets back to zero and the lap integer is incremented.

I was planning to compare these to work out player positions. Hopefully by putting them into arrays and then sorting them so it could tell me the player's positions in the race as the person with the high lap and checkpoint count would surely be the highest ranked.

Also to make the measuring of player positions more accurate I've measure the distance between checkpoints. At each checkpoint it works out how far the player is from the next point and using the distance from the previous to the next I'm able to generate a percentage which tells me how far the player is from the lap.

What I was hoping to do is create an integer worked out from the players race progress. So for example going through a checkpoint would increment the player's race progress integer by 100. If there were 12 checkpoint a complete lap would obviously be 1200. 2 laps would be 2400 and so on. By inverting the percentage I generated earlier it gives me the distance to the next checkpoint. so for example a player 75% towards the 4th checkpoint in their first lap would have an integer of 375, whereas a player 50% towards the first checkpoint in their second lap would have an integer of 1250.

I hope that logic made sense.

So what I'm essentially looking to create is a sort of table, using the player's object or even a unique player id as an index. And then to sort this table by the player position int.

I think this maybe possible through multidimensional arrays but I'm quite unsure. I've looked into associative arrays, dictionaries and hashtables but I'm still pretty unclear on what to do.

Would really appreciate being pointed in the right direction. Thanks!

# Answer
```
public class Racer
{
    public int CheckPoints { get; set; }

    public int Progress
    {
        get
        {
            return CheckPoints * 100;
        }
    }
}

```

I am assuming that you have a list of "racers" that you maintain. If that is the case, either on the update loop, or maybe only when they pass through a checkpoint, you can then update that list and order it by Progress descending.

```
YourRacersList = YourRacersList.OrderByDescending(x => x.Progress).ToList();

```

I am sure this can probably be optimized, but hopefully this will at least give you a starting point.
> 1 votes

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


# Question
Title: Box2D OpenGL debug renderer convert box2d coordinates to world space
I made an OpenGL 3.x renderer for Box2D's debug draw (b2Draw base class). Unfortunately I've tried for a while now to convert the box2D units, which are meters to my internal units which are pixels. I make 1 meter == 50 px, I set the sizes and positions just fine. It's only the debug renderer that is giving me trouble, because I don't know how to set the ortho and view matrix properly.

Basically I've got a camera which I center on the player's position each tick, the player's position being in pixels..so it could be say 2500x, 3200y. So the camera's view mat4 would be centered on that and the ortho is just set to the size of the screen.

So somehow I need to be able to turn this so that the position and the sizes are properly set. I'm using GLM for my matrix handling.

For example, I will see the physics debug data on screen if i set the ortho to be PIXELS\_PER\_METER (which is 50) for both x and y. But obviously this wouldn't map to worldspace, so my actual sprites won't have the physics bodies rendered where they are.

I've tried several things, including glm::scale, glm::translate with all kinds of different values and now I'm just out of ideas. Anything else I try results in no physics data to be drawn..

# Answer
well, turns out my real issue is not using meters as my internal units..that should solve everything.
> 1 votes

---
Tags: opengl, box2d, matrix, glm
---


title: transformations of matrices

text:
# Question
Title: transformations of matrices
I'm in the process of reading up on 3d matrices and trying to following this powerpoint and had a few questions as to how to exactly determine the type of transformation from a matrix.

If I have a matrix such as...

```
a 0 0
0 b 0
0 0 1
```

or

```
1 0 a
0 1 b
0 0 1
```

...would these be considered a translation by (a, b) vector?

Or a matrix such as...

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

... would this be considered rotation about Z-axis through the angle `a`?

Is there a better way to visualize these?

# Answer
The best way to gain intuition about how a matrix behaves is by determining its effect on the standard basis vectors:

```
     1        0        0
e1 = 0   e2 = 1   e3 = 0
     0        0        1

```

Since any 3D vector can be written as a combination of `a*e1 + b*e2 + c*e3`, if we know how a matrix changes these three vectors, we know how a matrix changes any vector.

So, to start off, let's examine the first matrix you have:

```
    a 0 0
M = 0 b 0
    0 0 1

```

We can see that

```
         a              0              0
e1 * M = 0     e2 * M = b     e3 * M = 0
         0              0              1

```

Hence, we see that `e1` gets scaled by `a`, `e2` gets scaled by `b`, and `e3` stays the same. Since we don't know whether or not `a` equals `b`, or even if they are equal to one, this is a skew matrix.

If we perform a similar analysis to the matrix

```
    1 0 a
M = 0 1 b
    0 0 1

```

we see that `e1` and `e2` do not change, but `e3` changes drastically. This means that every vector in the `XY` plane will remain the same, but every vector that has a nonzero `z` coordinate will become distorted! So, to answer your question, neither of these are translation matrices.

As your intuition might tell you by this point, you cannot translate a 3D vector using only 3x3 matrices. For that you need to use homogeneous coordinates.

I would suggest you go through these steps with the last matrix you have written. Spoiler alert: it is indeed a rotation about the z-axis.
> 4 votes

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


# Question
Title: Removing the titlebar while using slick2d?
I recently started using slick2D in my gaming programs and a problem I have is not having the ability to remove the border/titlebar. I usually do this to create my own cutom look/ interface but if I try:

```
this.setUndecorated(true);

```

It doesnt work.

How do you acheive this?

# Answer
Originally I was using

```
AppGameContainer app = new AppGameContainer(new Game());

```

to create my game. However I wanted to set the frame to be undecorated. So I searched around and found that if you changed

```
AppGameContainer app = new AppGameContainer(new WizardGame());

```

to

```
CanvasGameContainerapp = new CanvasGameContainer(new Game());

```

so that its now a canvas and then add it to a JFrame and set that JFrame to undecorated, you would get a undecorated slick2D program.

CODE:

```
public static void main(String[] args) throws SlickException {
    JFrame frame = new JFrame();
    CanvasGameContainer app = new CanvasGameContainer(new Game());
    frame.setUndecorated(true);
    frame.setVisible(true);
    frame.add(app);
    frame.setSize(500, 500);
    app.start();
}

```

The only problem that i have with it is that i have to click it once to render the images. If i don't it just has a black screen. This could be because of my other code but I don't think it should happen for anyone else.
> 0 votes

# Answer
Ok so here is a basic application that has the title bar removed

```
public static void main(String[] args){
    JFrame frame = new JFrame("Without Title Bar Frame");
    frame.setUndecorated(true);
    frame.setSize(400,400);
    frame.setVisible(true);
  }

```

**Paste the above code into a java class**

**Also be sure to import**

```
import javax.swing.JFrame;

```

You see how frame.setUndecorated(true); is straight after the instantiation of the frame? Place yours in the same place and you will have no issue at all :)

EDIT: here is what I found which may work.

http://slick.javaunlimited.net/viewtopic.php?f=3&t=4978

http://codebrocken.blogspot.com.au/2012/03/java-creating-undecorated-window-with.html?m=1

But as it states in that post it isn't support yet.
> 3 votes

---
Tags: java, interface, slick
---


title: Collision and gravity problems

text:
# Question
Title: Collision and gravity problems
So this is an easy question. I need to implement gravity in my game but where I'm stuck is what variables do I **need** in my Entity object for the calculations and a good algorithm that I can use for gravity and collision. The main reason why I'm stuck here is not just I'm implementing this into a huge program that handles the different states, windows, buttons and plenty of other stuff but all I got it the x, y, width, and height for my Entity and every time I try and calculate collision if the object hits a wall it stops, and I have no acceleration variables as I don't know how to use a algorithm with them so I'm guessing as I go and so my whole program is a mess. To make it clear of what I need someone to help me with is can you show me an example of how I would use my x, y, height, and width and move it around, use jumping, use gravity. I never really saw any of this so if someone knows how to do this, and or you have done this is a game before which you could show me what you did that would be great. I'm new to this so even a link is good. Thanks in advance!

# Answer
Not an entire answer, but a good tip: Add a bit to your entity called "falling" (or, inversely, "supported") which specifies whether or not gravity applies to the object. When an object is sitting on top of a stationary object you don't need to apply gravity effects to it, and you can set and unset that bit on events and collisions.
> 2 votes

---
Tags: 2d, java, game-mechanics, physics
---


# Question
Title: Why is my sky color calculation in Mathematica incorrect?
I'm trying to implement an algorithm to calculate sky color based on this paper (Perez' model). Before I start programming the shader I wanted to test the concept in Mathematica. There are already some problems I cannot get rid off. Maybe someone already has implemented the algorithm.

I started with equations for the absolute zenital luminances `Yz`, `xz` and `yz` as proposed in the paper (page 22). The values for `Yz` seem to be reasonable. The following diagram shows `Yz` as a function of the zenital distance of the sun for a turbidity `T` of 5:

The function gamma(zenith,azimuth,solarzenith,solarazimuth) calculates the angle between a point with the given zenital distance and azimuth and the sun at the given position. This function seems to work, too. The following diagram shows this angle for `solarzenith=0.5` and `solarazimuth=0`. `zenith` grows from top down (0 to Pi/2), `azimuth` grows from left to right (-Pi to Pi). You can clearly see the position of the sun (the bright spot, angle becomes zero):

The Perez function (F) and coefficients have been implemented as given in the paper. Then the color values Yxy should be `absolute value * F(z, gamma) / F(0, solarzenith)`. I expect those values to be within the range \[0,1\]. However, this is not the case for the Y component (see update below for details). Here are some sample values:

```
{Y, x, y}
{19.1548, 0.25984, 0.270379}
{10.1932, 0.248629, 0.267739]
{20.0393, 0.268119, 0.280024}

```

Here is the current result:

The Mathematica Notebook with all calculations can be found here and the PDF version here.

Does anyone have an idea what I have to change to get the same results as in the paper?

## C like code

```
// this function returns the zenital Y component for
// a given solar zenital distance z and turbidity T
float Yz(float z, float T)
{
    return (4.0453 * T - 4.9710)*tan( (4.0f/9-T/120)*(Pi-2*z) ) - 0.2155 * T + 2.4192
}

// returns zenital x component
float xz(float z, float T)
{
    return //matrix calculation, see paper
}

// returns zenital y component
float yz(float z, float T)
{
    return //matrix calculation, see paper
}

// returns the rgb color of a Yxy color
Color RGB(float Y, float x, float y)
{
    Matrix m; //this is a CIE XYZ -> RGB conversion matrix
    Vector v;
    v.x = x/y*Y;
    v.y = Y;
    v.z = (1-x-y)/y*Y;
    v = M * v; //matrix-vector multiplication;
    return Color ( v.x, v.y, v.z );
}

// returns the 5 coefficients (A-E) for the given turbidity T
float[5] CoeffY(float T)
{
    float[5] result;
    result[0] = 0.1787 * T - 1.4630;
    result[1] = -0.3554 * T + 0.4275;
    ...
    return result;
}

//same for Coeffx and Coeffy

// returns the angle between an observed point and the sun
float PerezGamma(float zenith, float azimuth, float solarzenith, float solarazimuth)
{
    return acos(sin(solarzenith)*sin(zenith)*cos(azimuth-solarazimuth)+cos(solarzenith)*cos(zenith));
}

// evalutes Perez' function F
// the last parameter is a function
float Perez(float zenith, float gamma, float T, t->float[5] coeffs)
{
    return (1+coeffs(T)[0] * exp(coeffs(T)[1]/cos(zenith)) *
           (1+coeffs(T)[2] * exp(coeffs(T)[3]*gamma) +
            coeffs(T)[4]*pow(cos(gamma),2))
}

// calculates the color for a given point
YxyColor calculateColor(float zenith, float azimuth, float solarzenith, float solarazimuth, float T)
{
    YxyColor c;
    float gamma = PerezGamma(zenith, azimuth, solarzenith, solarazimuth);
    c.Y = Yz(solarzenith, T) * Perez(zenith, gamma, T, CoeffY) / Perez(0, solarzenith, T, CoeffY);
    c.x = xz(solarzenith, T) * Perez(zenith, gamma, T, Coeffx) / Perez(0, solarzenith, T, Coeffx);
    c.y = yz(solarzenith, T) * Perez(zenith, gamma, T, Coeffy) / Perez(0, solarzenith, T, Coeffy);
    return c;
}

// draws an image of the sky
void DrawImage()
{
    for(float z from 0 to Pi/2) //zenithal distance
    {
        for(float a from -Pi to Pi) //azimuth
        {
            YxyColor c = calculateColor(zenith, azimuth, 1, 0, 5);
            Color rgb = RGB(c.Y, c.x, c.y);
            setNextColor(rgb);
        }
        newline();
    }
}

```

## Solution

As promised I wrote a blog article about rendering the sky. You can find it here.

# Answer
There are two errors in the matrix used for `xz`: 1.00166 should be 0.00166, and 0.6052 should be 0.06052.
> 4 votes

# Answer
It seems like it might be color value scaling issue?
> -2 votes

---
Tags: algorithm, sky
---


# Question
Title: How to draw an OpenGL object in another on Android? -> Eyes and Eyeballs
As i allready wrote in another question:

> I'm working on OpenGL since a Week, so i'm new to the most stuff. (also my englisch isn't the best. Hop you can understand the most anyway) So i'm working on an Tamagotchi App for a school project and want to make it with OpenGL. -\> How to change/modify or animate an existing OpenGL object on Android?

So this is a further question.

My Tamagotchi is haveing to eyes. Like this:

To make it look real i want the eyes to blink and the eyeballs to move arround. But the question here is what happens with the eyeball when the eyes are closed. In my Situation you woud not see the eyeballs because they are the same color then the body of the Tamagotchi. But i want the eyeballs to be a part of the eye. So if the Eye is closing the eyeballs shoud disapear where the eyes are closed whereever the eyeball is at the moment.

Here you can see the eye closed (down scaled y) but the eyeball is still visible....

I want the eyeball to be cut of or not shown where the eye is closed like this:

But i have no idear how to solve this.

**Edit** Here is my Code for someone who want to look at it. But i think it is not necessary.

```
public class GLEyes {

private int points = 1000;
private float vertices[]={0.0f,0.0f,0.0f};
private FloatBuffer vertBuff;

//Der Kreis wird von der Mitte der Fläche gezeichnet

public GLEyes(){

    vertices = new float[points * 2];
    for(int i=0; i< (points+3); i+=3)
    {
      double rad = 2*(Math.PI *i) / points; //Berechnung des radius

      vertices[i]=(float)Math.cos(rad);     //X Achsen Abschnitt
      vertices[i+1]=(float)Math.sin(rad);   //Y Achsen Abschnitt
      vertices[i+2]=0;                      //Z Achsen Abschnitt wird nur für 3D gebraucht
    }

    ByteBuffer bBuff=ByteBuffer.allocateDirect(vertices.length*4);
    bBuff.order(ByteOrder.nativeOrder());
    vertBuff=bBuff.asFloatBuffer();
    vertBuff.put(vertices);
    vertBuff.position(0);
}

public void draw(GL10 gl){

    lefteye(gl);
    righteye(gl);

}

private void lefteye (GL10 gl){
    gl.glPushMatrix();
    gl.glTranslatef(1, 1, 0);
    gl.glScalef(0.5f, 0.45f, 1.0f); //Skalierung einstellen
    gl.glColor4f(0.0f,0.0f,0.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();

    gl.glPushMatrix();
    gl.glTranslatef(1, 1, 0);
    gl.glScalef(0.1f, 0.1f, 1.0f); //Skalierung einstellen
    gl.glColor4f(1.0f,1.0f,1.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();
}

private void righteye (GL10 gl){
    gl.glPushMatrix();
    gl.glTranslatef(-1, 1, 0);
    gl.glScalef(0.5f, 0.45f, 1.0f); //Skalierung einstellen
    gl.glColor4f(0.0f,0.0f,0.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();

    gl.glPushMatrix();
    gl.glTranslatef(-1, 1, 0);
    gl.glScalef(0.1f, 0.1f, 1.0f); //Skalierung einstellen
    gl.glColor4f(1.0f,1.0f,1.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();

}

}

```

# Answer
For 2D Graphics you can use the Painter's Algorithm, or alternatively the Reverse Painter's Algorithm. Means you have to draw the pupil first, then the face. The face will be drawn over the pupil this way.

For 3D Graphics that's not sufficient, you need to give everything a Z-Coordinate and activate Depth Testing.
> 1 votes

---
Tags: android, opengl-es
---


# Question
Title: How to Render Cylinder with built in function D3DXCreateCylinder in Directx9 with Delphi-Xe2 and JEDI?
I'm new to Directx and i want to render Cylinder using "D3DXCreateCylinder" function. I using Delphi Xe2 and JEDI for DirectX9.

# Answer
> 0 votes
First declare direct3D Object, RenderingDevice and Mesh as global variable. In order to use DirectX in the Delphi - Pascal, add Direct3D9, D3DX9, DXTypes in USES clause.

```
uses Winapi.Direct3D9, Winapi.D3DX9, Winapi.DXTypes;

```

Global Declaration:

```
const
   D3DFVF_CUSTOMVERTEX = (D3DFVF_XYZ or D3DFVF_NORMAL);
var
   objD3D: IDirect3D9 = nil;
   dvcRender: IDirect3DDevice9 = nil;
   vbD3D: IDirect3DVertexBuffer9;
   mesh: ID3DXMesh;

```

Create Function for Initialization of Direct3D:

```
function TfrmDirectX.initD3D(hWindow: HWND): HRESULT;
var
   paramD3D: TD3DPresentParameters;
begin
   Result := E_FAIL;
   objD3D := Direct3DCreate9(D3D_SDK_VERSION);
   if (objD3D = nil) then Exit;

   FillChar(paramD3D, SizeOf(paramD3D), 0);
   paramD3D.Windowed := True;
   paramD3D.SwapEffect := D3DSWAPEFFECT_DISCARD;
   paramD3D.BackBufferFormat := D3DFMT_UNKNOWN;
   paramD3D.EnableAutoDepthStencil := True;
   paramD3D.AutoDepthStencilFormat := D3DFMT_D16;
   Result := objD3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWindow,
                             D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                             @paramD3D, dvcRender);
   if Failed(Result) then Exit;
   dvcRender.SetRenderState(D3DRS_ZENABLE, iTrue);
   Result := S_OK;
end;

```

I will render 3D on TPanel component of the Delphi. So i passing Handle of TPanel Component as parameter. Another Function to setup a Matrix:

```
procedure TfrmDirectX.setupMatrices();
var
   vEyePt, vLookatPt, vUpVec: TD3DVector;
   matView: TD3DMatrix;
   matProj: TD3DMatrix;
begin
   vEyePt:= D3DXVector3(spnCX.Value, spnCY.Value, spnCZ.Value);
   vLookatPt:= D3DXVector3(spnLX.Value, spnLY.Value, spnLZ.Value);
   vUpVec:= D3DXVector3(0.0, 1.0, 0.0);
   D3DXMatrixLookAtLH(matView, vEyePt, vLookatPt, vUpVec);
   dvcRender.SetTransform(D3DTS_VIEW, matView);

   D3DXMatrixPerspectiveFovLH(matProj, D3DX_PI/4, 1.0, 1.0, 100.0);
   dvcRender.SetTransform(D3DTS_PROJECTION, matProj);
   mesh.DrawSubset(0);
end;

```

And Last procedure for Rendering:

```
procedure TfrmDirectX.render();
begin
   // Call function to create Cylinder and return Mesh.
   D3DXCreateCylinder(dvcRender, 1, 1, 2, 8, 8, mesh, nil);
   dvcRender.Clear(0, nil, D3DCLEAR_TARGET OR D3DCLEAR_ZBUFFER,
              D3DCOLOR_XRGB(255, 0, 0), 1.0, 0);
   if Succeeded(dvcRender.BeginScene) then begin
      setupMatrices();
      dvcRender.EndScene;
   end;
   dvcRender.Present(nil, nil, 0, nil);
end;

```

## D3DXCreateCylinder Function

Uses a left-handed coordinate system to create a mesh containing a cylinder.

Syntax

```
HRESULT D3DXCreateCylinder( LPDIRECT3DDEVICE9 pDevice,
FLOAT Radius1,
FLOAT Radius2,
FLOAT Length,
UINT Slices,
UINT Stacks,
LPD3DXMESH *ppMesh,
LPD3DXBUFFER *ppAdjacency
);

```

Parameters:

pDevice \[in\] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created cylinder mesh.

Radius1 \[in\] Radius at the negative Z end. Value should be greater than or equal to 0.0f.

Radius2 \[in\] Radius at the positive Z end. Value should be greater than or equal to 0.0f.

Length \[in\] Length of the cylinder along the z-axis.

Slices \[in\] Number of slices about the main axis.

Stacks \[in\] Number of stacks along the main axis.

ppMesh \[out\] Address of a pointer to the output shape, an ID3DXMesh interface.

ppAdjacency \[out\] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Value: If the function succeeds, the return value is D3D\_OK.

After Creating All the Function and Procedure first call InitD3D(hWindow) and then call Render().

---
Tags: directx, directx9, delphi
---


title: Exclusive mouse movement with WM_INPUT

text:
# Question
Title: Exclusive mouse movement with WM_INPUT
Microsoft seems to recommend using `WM_INPUT` for input. I want to only get relative mouse input and hide the mouse cursor all together for a short while (For gesture based input). However, using `RIDEV_CAPTUREMOUSE|RIDEV_NOLEGACY` while registering the input device only prevents the mouse clicks to other windows, but the mouse cursor is still visible and not constrained to my window. How can I hide it and make it reappear exactly where I left off when my input capture began after the short while?

I know this has been asked before in the context of FPS controls, but it always seemed to be in a different context, mostly with APIs that already implement a mouse grab like this.

It was also mentioned that you could hide the cursor and reset it to its window's center after every move. However, `AFAIR`, `DirectInput` let you grab the mouse cursor exclusively. So since that was deprecated in favor of `WM_INPUT`, is the "old way" without `DX` the way to go again, or is there something new that works well with `WM_INPUT`?

Thank you!

# Answer
> 1 votes
If I understand you correctly, you simply want to hide the mouse when your gesture starts, and then make the mouse appear again on the position it disappeared.

Get the mouse position before hiding:

```
POINT posRelative;
POINT posAbsolute;
GetCursorPos(&posAbsolute);
posRelative.x = posAbsolute.x;
posRelative.y = posAbsolute.y;
ScreenToClient(hwnd, &posRelative);

```

then show / hide it:

```
bool hideCursor = true;
while(hideCursor  != IsRealCursorHidden())
{
    ShowCursor(hideCursor  ? 0 : 1);
}

bool IsRealCursorHidden()
{
    int internalCount = ShowCursor(0);
    internalCount = ShowCursor(1);
    return (internalCount < 0 ) ? true : false;
}

```

and then show the cursor at the desired original position again:

```
SetCursorPos(pos.x, pos.y);

```

**Edit:**

GetCursorPos will be in screen space, so if you have a different resolution you will have to take that into account.

# Answer
> 0 votes
> The advantage to using WM\_INPUT is that your game receives raw data from the mouse at the lowest level possible.

WM\_INPUT is only for raw input, it doesn't know of or care about the cursor and absolute coordinates. Cursor specific things are specific to the windowing system, so for PC you can use the standard methods of manipulating the cursor. It is C# but translating it to unmanaged code shouldn't be hard.

```
[DllImport("user32.dll", EntryPoint = "SetCursorPos")]
public extern static Int32 SetCursorPosition(Int32 x, Int32 y);

[DllImport("user32.dll")]
static extern int ShowCursor(bool bShow);

```

---
Tags: c++, c, mouse, winapi
---


# Question
Title: Ideas wich design patterns apply in my school assignment
For a assignment for school i've to develop a game in Microsoft XNA 4. Let me first clear out that my intention of this post is NOT to give me codes. I want to figure out things by my self. The intention of this post is to help me and give me advice wich design patterns may be better to apply in wich situation.

This game should use the following design patterns:

* strategy
* factory
* decorator
* singleton
* observer
* template

The assignment is as follow:

In this game the player should avoid the attack from his enemies who want to attack his spaceship. The enemies have their own way of attack and movement.

When the game starts the player has one cannon who can shoot bullets each 0.2 seconds. The spaceship can move horizantally with the keyboard. With the spacebar the player kan shoots bullets.

There are 3 kind of enemies who have their own attack and the way they move.

* Chure : Moves horizantally from left to right, each time when the chure hits the edge
he moves down and again he move horizontally but this time in the opposite direction (thus from right to left). Each chure drops at any time (random) a bomb. Each level the speed of the drop will increase.
* Thege: Moves from the corner of the stage diagonal to the player. When the Thege hits the player, the player loose one life and starts the level again. When the Thege don't hit the player and reach the bottom of the stage he will remove from the stage and won't come back again in that level.
* Sinode : Moves from top to bottom of the stage, when the Sinode reach the bottom of the stage hi moves the opposite direction (from bottom to top). The Sinode stays on the stage as long as the player didn't shoot him. When the player shoots the Sinode he will be remove from the stage.

Each enemie can carry an upgrade wich will be released when he will be shot by the player. either the enemie has a upgrade or not has been choosen randomly. There are three kinds of upgrades. The player can use his spaceship but once expand with each type of upgrade. If the player already has a upgrade the upgrade will remove from the stage.

The three type of upgrades are:

* Lasers (Specs aren't important)
* Rockets (Specs aren't important)
* Guided missile (Specs aren't important)

some conditions to the game: \- The game consists of 3 levels \- Each player starts with 3 life \- The level will be ended when all of the enemies are destroyed or not visible on the stage.

Now i've some ideas wich design pattern will be good by wich scenario but i would be gratefull if u guys can help me out how i can implement the factory and the observer pattern in this case and maybe help me out and give advice how i can implement the rest of the patterns.

Thank u

# Answer
> 1 votes
Here are just some examples of how I might apply the given design patterns. This is with very little understanding of the details of the assignment, and with very little reading of the above post.

- Strategy - Enemy movement (ie. which type of enemy).
- Factory - Creation of enemies.
- Decorator - Applying upgrade functionality when upgrades are equipped.
- Singleton - ***NEVER USE SINGLETONS! CONSCIENTIOUSLY OBJECT!*** Or, use a singleton scorekeeper.
- Observer - Enemy death notifications (protip: have the scorekeeper listen to enemy death events!)
- Template - Baseline enemy movement code.

Now, also keep in mind that design patterns are rather specialized for their purposes, and should NOT be a one-size-fits-all solution.

> The most important part of design patterns is being able to figure out **when** and **how** to use them **on your own**.

That being said, my typical response to questions such as these would be "Figure it out on your own" and "I'm not here to do your homework for you", but since you asked for advice on specifically that, I'm going to assume the purpose of the assignment is to get you to think critically about what the design patterns are, and when to apply them. If you have to ask here, then it's either a shortcoming on your part due to inadequate research, or on your professor's part due to inadequate education on those core design patterns. Take my suggestions with this warning: *Design patterns should be used with care and understanding.*

---
Tags: xna, design-patterns
---