# Question
Title: What is the appropriate way of placing game objects in a 2d game?
I'm developing a 2d game for Android.It will be an endless game.I have some items like coins ,plants and other special items.How can i place them effectively?Are there any algorithm or any suggestion for this?

I'm already know that i have to use random numbers for placing them along x and y axis.It's important to not placing two different item at the same x and y position.

# Answer
> 5 votes
I've used the following approach to generate apples on a snake clone. It's very simple, although it has some potential problems depending on your game requirements. But if you know will always be a lot more free locations that occupied locations, it should be enough in practice.

Generate a random location for the X and Y axis separately based on the size of the map, but wrap it in a `do...while` loop that automatically retries whenever the location is already occupied. Something like:

```
// Find valid location
int x, y;
do {
    x = random(0, width);
    y = random(0, height);
} while(IsLocationOccupied(x, y))

// Create object there
SpawnObjectAt(x, y);

```

The implementation of `IsLocationOccupied` depends on your game. For instance, for a tile-based game you could simply check the contents of the tile at that location. For example:

```
bool IsLocationOccupied(int x, int y)
{
    return map[x, y] != TileType.Empty;
}

```

For a non-tile based game, you could iterate over all your objects and check if any of them would intersect with a new object spawning at that location. For example:

```
bool IsLocationOccupied(int x, int y)
{
    Rectangle newBounds = new Rectangle(x, y, objectWidth, objectHeight);
    foreach(Entity entity in entities)
        if(entity.bounds.Intersects(newBounds))
            return true;
    return false;
}

```

A safer alternative is to somehow keep a list of all the free locations in the screen, and remove one element at random from the list when you need to spawn a new object. This is great in a tile-based game, but even in a continuous environment you can still divide it into an imaginary grid to limit the number of locations.

# Answer
> 3 votes
Since the game world is endless, I would chunk in up into regions. When the player moves close to the edge of the region in one direction, you can generate the objects in the next region in that direction. As the games runs, you can adjust the level play by controlling how many "good" and "bad" objects you place in the upcoming region to keep the player engaged. For example, if the player's "health" is slipping, you may want to adjust the number of "bad" object down or increase the number of "good" objects in the next region he encounters. David's answer is great for spawning objects. You may want to adjust it slightly so that you don't put your game objects too close together or too far apart. Instead of testing for intersection, just test a bigger area around the potential location. Consider having a few dozen or so predefined regions that are "fun" to play.

---
Tags: 2d, android, algorithm
---


# Question
Title: What could cause a pixel shader to paint outside the lines of the vertex shader output?
From what I understand, the pixels that a pixel shader operates on are specified implicitly by the SV\_POSITION output (in DirectX) of the vertex shader. What then could cause a pixel shader to render in the middle of nowhere?

I used the new Visual Studio 2012 graphics debugger to visualize my vertex and pixel shader output. This is the output from a DrawIndexed() call that draws a cube:

The pink part is the rendered output of the pixel shader, which takes the cube on its left as its input.

The vertex shader code:

```
cbuffer Buf { float4x4 final; };

struct In
{
    float4 pos:POSITION;
    float3 norm:NORMAL;
    float2 texuv:TEXCOORD;
};

struct Out
{
    float4 col:COLOR;
    float2 tex:TEXCOORD;
    float4 pos:SV_POSITION;
};

Out main(In input)
{
    Out output;
    output.pos = mul(input.pos, final);
    output.col = float4(1.0f, 0.5f, 0.5f, 1.0f);
    output.tex = input.texuv;

    return output;
}

```

And the pixel shader:

```
struct In
{
    float4 col:COLOR;
    float2 tex:TEXCOORD;
    float4 pos:SV_POSITION;
};

float4 main(In input) : SV_TARGET
{
    return input.col;
}

```

The raster stage is the only thing between the vertex shader and the pixel shader, so my suspicion is that it's some raster stage settings. But the raster stage shouldn't change the shape of the vertex shader output so drastically, should it?

# Answer
> 2 votes
I just had a look at my own vertex shaders, the difference is likely in the matrix you use.

If you are working with the transpose of the matrix, vector\*matrix is appropriate, else you will need to do matrix\*vector.

```
PS_IN VS(VS_IN input)
{
    PS_IN output;
    float4x4 WVP = transpose(VP);
    output.pos = mul(input.pos, WVP);
    return output;
}

```

Does exactly the same as

```
PS_IN VS(VS_IN input)
{
    PS_IN output;
    output.pos = mul(VP, input.pos);
    return output;
}

```

# Answer
> 0 votes
Assuming the debug images above are correct, there is either

a) something wrong with the way the images you are debugging are being selected/updated, or b) The debug image of the vertex shader is not showing the transformations being applied, for whatever reason. As a rule, whatever comes out of the vertex shader should come into the pixel shader as a filled triangle with the exact coordinates specified by the vertex shader. c) You are not building with the correct settings for debugging/performance testing

Easiest fix: use a working project (such as one of the DirectX Samples), and get that working properly, then isolate the problem if you can.

---
Tags: directx, shaders
---


# Question
Title: Higher Performance With Spritesheets Than With Rotating Using C# and XNA 4.0?
I would like to know what the performance difference is between

1. using multiple sprites in one file (sprite sheets) to draw a game-character being able to face in 4 directions and
2. using one sprite per file but rotating that character to my needs.

I am aware that the sprite sheet method restricts the character to only be able to look into predefined directions, whereas the rotation method would give the character the freedom of "looking everywhere".

---

Here's an example of what I am doing:

1. Single Sprite Method

Assuming I have a 64x64 texture that points north.

So I do the following if I wanted it to point east:

```
spriteBatch.Draw(
    _sampleTexture,
    new Rectangle(200, 100, 64, 64),
    null,
    Color.White,
    (float)(Math.PI / 2),
    Vector2.Zero,
    SpriteEffects.None,
    0);

```
2. Multiple Sprite Method

Now I got a sprite sheet (128x128) where the top-left 64x64 section contains a sprite pointing north, top-right 64x64 section points east, and so forth.

And to make it point east, i do the following:

```
spriteBatch.Draw(
    _sampleSpritesheet,
    new Rectangle(400, 100, 64, 64),
    new Rectangle(64, 0, 64, 64),
    Color.White);

```

So which of these methods is using less CPU-time and what are the pro's and con's?

Is .NET/XNA optimizing this in any way (e.g. it notices that the same call was done last frame and then just uses an already rendered/rotated image thats still in memory)?

# Answer
> 3 votes
Without access to the XNA source for the SpriteBatch object it could be hard to tell. But the main difference is in the transformation.

When you render a sprite with SpriteBatch it will create a quad and place it in a buffer. The vertices of this quad will have to be transformed to put the sprite in the position you specified.

When you use the SpriteBatch.draw() method in the first example you provide two rectangles. It is from the first one that your sprite quad will be constructed and you should be able to see how constructing the vertex coordinates from a rectangle would be trivial.

In the second instance an extra step will have to be taken because of the rotation. To handle the rotation a transformation matrix will be constructed and each vertex of the quad will be transformed using this matrix.

Now, it may be that in both cases a transformation matrix is created, but in the second method an extra step will have to be taken to add rotation to that transformation matrix.

A good profiler will give you a better idea of what is going on, although the reality is that you are most likely not rendering enough objects to see an difference when you put this method to work on a real project and you will find that artistic requirements will dictate which you will use at that time.

I would also like to point out that if you are concerned over this because it was a common technique back the in the glorious 2D era you don't really have to worry as you have the power at your disposal to forget about it. The main reason it that this was a problem on older hardware seems to be because the creation of a rotation matrix would most likely involve the use of many trigonometric functions which are not trivial operations.

# Answer
> 4 votes
Using a sprite sheet reduces the need for the computer to load a new/different image in order to draw on the screen.

Here is an article which shows the performance differences in XNA (in the emulator and on a device) as well as the animation class used.

# Answer
> 4 votes
Hard to say without actually profiling it but some information that might help:

* When you do not use the `rotation` parameter or leave it as `0`:

+ The rotation transformation is still applied, but `SpriteBatch` handles it as a **special case** which costs one `Math.Cos` and one `Math.Sin` less *for each sprite* being drawn, because it already knows that the sine and cosine of zero are 0 and 1 without having to calculate it.
* When you do not use the `sourceRectangle` parameter or leave it as `null`:

+ `SpriteBatch` still fill outs the rectangle internally using the texture size as default values. There is **no difference** in the rendering part of the algorithm, which still uses these values to calculate the correct texture coordinates and sprite size.

Since trigonometry functions are somewhat expensive, and using a source rectangle requires the same amount of work as not using one, I think using the sprite sheet approach will probably be a bit faster than rotation, although the difference is probably negligible.

# Answer
> 2 votes
**This is such a horrible, terrible micro-optimisation that you should not be pursuing it!**

On the CPU, selecting a rectangle will be faster by a tiny, *tiny* amount (as David Gouveia has already pointed out, with a rotation of exactly 0, XNA skips two trig operations required to rotate the vertices).

On the GPU you are using more RAM by using a sprite sheet. The difference in size could conceivably cause a similarly minuscule performance difference.

Because each method alters performance by an extremely small amount and affects both CPU and GPU - which is better will almost certainly depend on the CPU/GPU combination in use and what the rest of your app is doing.

Certainly any measurements from a profiler will be meaningless (unless you are targeting fixed hardware like the Xbox 360).

To answer your last question: No, XNA does not cache sprite batch `Draw` operations. The vertex buffer is recalculated each frame.

***So what should you do?***

If you are actually at a stage where you legitimately need to consider these performance implications (eg: you need to draw 10000+ copies of your character), you should stop using `SpriteBatch` entirely. If you implement an alternative that handles only your specific case, and you have the necessary skills, you can write something that performs considerably faster.

Assuming you don't actually need the performance optimisation, which method should you choose?

**Use the rotation method!** Firstly it matches conceptually with what you are doing - a rotation. And secondly it reduces the amount of content you need to create.

---
Tags: xna, c#, 2d, performance, spritesheet
---


title: Smooth vector based jump

text:
# Question
Title: Smooth vector based jump
I started working on Wolfire's mathematics tutorials. I got the jumping working well using a step by step system, where you press a button and the cube moves to the next point on the jumping curve.

Then I tried making the jumping happen during a set time period e.g the jump starts and lands within 1.5 seconds. I tried the same system I used for the step by step implementation, but it happens instantly. After some googling I found that Time.deltatime should be used, but I could not figure how. Below is my current jumping code, which makes the jump happen instantly.

```
 while (transform.position.y > 0)
 {
   modifiedJumperVelocity -= jumperDrag;
   transform.position += new Vector3(modifiedJumperVelocity.x, modifiedJumperVelocity.y, 0);
 }

```

Where modifiedJumperVelocity is starting vector minus the jumper drag. JumperDrag is the value that is substracted from the modifiedJumperVelocity during each step of the jump. Below is an image of the jumping curve:

# Answer
> 4 votes
I believe the reason this is happening "instantly" is because you seem to be using a while loop inside your update loop. That would cause your characters position to go through the entire jump inside a single frame, meaning it would only be drawn at the end of the jump. Try something like this:

```
if (transform.position.y > groundHeight)
 {
   modifiedJumperVelocity -= jumperDrag;
   transform.position += new Vector3(modifiedJumperVelocity.x, modifiedJumperVelocity.y, 0);
 }

```

# Answer
> 2 votes
The answer given by Byte56 describes one fundamental mistake in your code that you must fix. But afterwards you'll still want to factor in the delta time into your movement otherwise it is likely to occur too fast and depend on the framerate of the game.

In that regard, I think you're trying to implement euler integration (although if you read that article you will see that he recommends using a more complicated method). It's usually implemented like this:

```
velocity += acceleration * deltaTime
position += velocity * deltaTime

```

Which in your example would become the following (considering `jumperDrag` to be your acceleration):

```
modifiedJumperVelocity -= jumperDrag * deltaTime;
transform.position += new Vector3(modifiedJumperVelocity.x, modifiedJumperVelocity.y, 0) * deltaTime;

```

Afterwards, just tweak your initial velocity and acceleration values to change the duration of the jump.

By the way I think `jumperDrag` would make more sense being called `gravity` and defined as a vector pointing donwards, so that you can get rid of the minus sign. And you might as well use `Vector3` everywhere to avoid the conversion at the end and simplify everything.

---
Tags: unity, vector, jumping
---


# Question
Title: How should I store a Game Database on Android?
I'm looking at creating a game for Android and while I have most of the ins and outs worked out, the one thing I'm struggling with is how to store data for the game.

Ultimately, the game will be based off of a lot of pre-defined data and statistics so the obvious choice to me would be something like SQLite, but as I'm pretty new to the realm of Android and Game Development, I'm not 100% certain if this is the right route to follow.

The data will be general pre-defined data as well as player data (along the lines of careers stats - what place finished, etc).

I was wondering if there was a better/best practice solution that wasn't SQLite and that would provide said functionality and if so, could you point me in the right direction?

# Answer
I am just doing one which simply creates xml files. For example an entire level is saved as an xml file and then reloaded when needed, unless the user has finished the level, then a new random one is created. Every object is one tag with its attributes like

```
<Object name="car" color="blue" maxspeed="300" />

```

I think this is more simple way to do it when one does not need to do a lot read/write operations, i.e. does not actually need a fast database.

But for the smaller amount of data user preferences saved in the private application space can do.
> 3 votes

# Answer
Embedding a SQLite database into your application isn't too hard. There are lots of examples on the web, such as http://www.vogella.com/articles/AndroidSQLite/article.html XML (as suggested by Lumis) or plain text file could also work. For an example of XML, see the following: https://stackoverflow.com/questions/10535472/android-development-where-to-put-static-key-value-pairs. For the flat text file, you could use a simple stringtokenizer to seperate your key/value pairs.
> 0 votes

---
Tags: android, databases, sql
---


title: How to draw a global day night curve

text:
# Question
Title: How to draw a global day night curve
I see many applications which have world-clock map, and I would like to make my own to enhance some of my mobile apps. I wonder if anybody has any knowledge where to start, how to draw a curved shadow representing the dawn and the sunset on the globe. See the example:

http://aa.usno.navy.mil/imagery/earth/map?year=2012&month=6&day=19&hour=14&minute=47

I think that this curve goes up and down and creates an artic day/night etc Perhaps there is some acceptable approximation formula without a need to load data for each our and each global parallel and meridian...

# Answer
You can calculate this using some basic trigonometry.

Here is a very nice and well documented explanation of how to calculate the length of day and the duration of twilight for any latitude and for any day of year.

You can also read this discussion on http://mathforum.org which mention an article in *Ecological Modeling*, volume 80 (1995) pp. 87-95, called "A Model Comparison for Daylength as a Function of Latitude and Day of the Year."

> This article presented a model that apparently does a very good job of estimating the daylight - the error is less than one minute within 40 degrees of the equator, and less than seven minutes within 60 degrees and usually within two minutes for these latitudes.
>
> I figured that if other people were having trouble finding this information, too, maybe it would be worth saving them some time by letting you know what I found. So, here's the model:
>
> **D** = daylength

> **L** = latitude

> **J** = day of the year
>
> **P** = asin(.39795*cos(.2163108 + 2*atan(.9671396\*tan(.00860(**J**-186)))))
>
> **D** = 24 - (24/pi)*acos( (sin(0.8333*pi/180) + sin(**L**\*pi/180)*sin(**P**)) / (cos(**L***pi/180)\*cos(**P**)) )
>
> Use a radian mode here, but latitude should be entered in degrees.

*Note, that the day of year **J** probably does not start with the January 1st, but with the day of the winter solstice in the first year a four years cycle.*

Using this, you should be able to generate the day/night curves you need so it *almost* matches the reality.
> 9 votes

---
Tags: c++, java, javascript
---


# Question
Title: Basic AI FSM - Handling state transition
I'm starting to study on how to implement game AI, and it seems to me that a very simple FSM for my Pong demo would be a nice way to start.

My vision on implementing this would be to have a basic state interface and a class for each state, then the NPC would have an instance of the current state. The class should have an update method and directions on wich state to go next, depending on the event received.

The question is: How do I handle this event? Should I have a regular addEventListener and a costum event system? Or should I check on update for the things that could change the current state?

I'm feeling a bit lost, I feel I have a good grasp on the FSM concept but a good implementation seems tricky, thanks in advance.

# Answer
> 1 votes
There are many different implementations and variations but I find the following works like a charm:

You would have your StateManager class. This would control the overall FSM. Then you have a state interface. Each state would implement after this interface.

```
// The manager that controls the whole FSM.
StateManager
// The interface class. Would provide mostly virtual methods for use in sub classes.
IState
// Every state would extend the interface and
// inherit it's default members.
SomeState : public IState

```

You could have the following methods in each state to begin with:

```
Update()
Draw()
OnEnter()
OnExit()

```

Your Manager Class would have these methods to start:

```
Push(string state);
Switch(string state);
Pop();
Register(state);
Remove(string state);
Next();
Back();
CreateOperation();
HandleOperations();

```

**Register:** Takes a state's instance and stores it into an array. Remember that this would not be the fsm stack, only the registration stack. It would map the class to a string that you could identity the state as.

**Remove:** Removes a state from the registration stack.

**Push:** Takes a string (from the registration stack) and takes the stack from the registration array and pushes it to the top of the state stack.

**Switch:** Replaces the current level state in the stack with one from the registration stack.

**Pop:** Pops an item from the state stack.

**Next:** Would enable the next state under the current one.

**Back:** This would enable the previous state, and disable the current one.

**CreateOperation:** This is the secret. You will want to store a queue for all the current operations. CreateOperation would add a new operation to the queue. Each operation would link to the appropriate method. (e.g Push operation would call the Push(); method)

**HandleOperation:** You would call this after the update methods. Since you want to wait until the game has been updated before messing around with the states. This method would go through the queue starting with the first and handle the operation.

---

**Delays** You could implement a delay event system. To where the handleOperation would wait so many seconds or start a custom timer of some sort. This could provide you with additional functionality and methods such as OnDelayStart, OnDelayFinish. Animations are a great result of this.

Every time you call the Push method (through an operation) the OnExit method for the currently active state would also be called just before the switch. The same would be true for Pop(), Next(), and Back(). OnEnter would be called right when you switch to that state.

---

**Opacity:** You might want sub-states(states under the top-most state in the stack) to be able to draw but not update. But some states might restrict lower states in the stack to draw. You could implement an opacity meter. 1 = Drawable() and 0 = Can't Draw().

You can also extend this use methods such as OnPause(), and OnResume(). When sub-states are allowed to draw but cannot update; you would call the OnPause() right when that occurs. When they are allowed to update again you could call OnResume().

There are many different ways of achieving a good FSM but imo this has the greatest flexibility. You could even extend this even more to suite your needs.

Note: The states themselves handle the transition to the next states. Since the manager does not know when or how each state ends and then switches to the next state. Only the states themselves know when or how to move on.

---
Tags: flash, ai, actionscript-3, fsm
---


# Question
Title: Can you run OpenGL 2.0 on modern machines?
I'm looking to get into 3d with OpenGL, using SDL to help with other stuff.

I found plenty of good tutorials (lazyfoo is a big one), but "Learning Modern 3d Graphics Programming" uses a newer version of openGL that I'm not able to run!

I opened up OpenGL extensions viewer, and I can only run OpenGL 2.0, whereas most tutorials are in higher versions.

I ask this because I've heard that just about everything in 2.\* got depreciated in the newer versions, so I'm worried that my code might not work.

I'm looking at a few other tutorials, but I'm so used to SDL that those just confuse me...

So should I bother trying to do graphics programming now, or should I just wait until I can upgrade my computer?

# Answer
Modern drivers / video cards are able to choose OpenGl implementations. Whether it's only using features described in these versions or setting it. So you should be fine going for 2.0 since majority of video cards support this version.
> 3 votes

# Answer
When you create an OpenGL window, you choose the context you want. Here's a possible way to do that on Windows (when creating a Win32 window):

```
HGLRC tempcontext = wglCreateContext(hDC);
wglMakeCurrent(hDC, tempcontext);

GLenum status = glewInit();
if (status != GLEW_OK)
{
    char error[256];
    sprintf(error, "%s", glewGetErrorString(status));
    MessageBoxA(NULL, error, "GLEW error", MB_OK | MB_ICONEXCLAMATION);
    return GL_FALSE;
}

int supported = wglewIsSupported("WGL_ARB_create_context");
if (supported == 1)
{
    LOG_INFORMATION("Creating OpenGL 3.1 context.");

    int attribs[] =
    {
        WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
        WGL_CONTEXT_MINOR_VERSION_ARB, 1,
        WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
        0
    };

    hRC = wglCreateContextAttribsARB(hDC, 0, attribs); CGLE();
    wglMakeCurrent(NULL, NULL);
    wglDeleteContext(tempcontext);
    wglMakeCurrent(hDC, hRC);
}
else
{
    LOG_INFORMATION("Creating OpenGL 2.1 context.");

    hRC = tempcontext;
}

```
> 1 votes

---
Tags: opengl
---


title: Unity: Spin wheels to move vehicle

text:
# Question
Title: Unity: Spin wheels to move vehicle
I am just getting started with Unity and I'd like to ask a question. If I have a "Vehicle" object that has two children: "FrontWheel" and "BackWheel" (both 'wheels' are cylinders), how should I set everything up such that I can move the entire vehicle by turning its wheels?

When I apply a torque to "FrontWheel", the vehicle starts to move, but instead of the whole thing the moving together, the chassis is rolling on the cylinders and eventually falls off.

How can I prevent it from doing that?

# Answer
There are so many special case considerations with the simulation of wheeled vehicle physics that you are unlikely to get a satisfying result by simply torquing cylindrical collision primitives. You should consider instead using the special Wheel Collider component.
> 2 votes

---
Tags: unity, vehicle
---


# Question
Title: Implementing powerups for my Breakout clone
I'm making a simple Breakout clone in Python that will have very many powerups/powerdowns (so far I came up with 26). Some will affect the paddle (paddle missile, two paddles, short paddle, etc.), some will affect the ball (slow ball, destructo-ball, invisible ball, etc.), some will affect the bricks (brick scramble, move up, bricks indestructible, etc.), and some will affect other game aspects (extra life, more points, less points, etc.). I'm pretty sure I have the code to draw the falling powerups and test for collisions with the paddle down, but I'm confused about how to code the effects of the powerups. Since there are very many powerups, it seemed inefficient to add specific methods to each component as done in this tutorial. However, I can't think of an other ways to implement the powerups. I found a page that hints at some way to design powerup behavior using classes, but I'm at a loss for how to do that. (A short example would help.) Please give me a short code example of another way to implement the effects of the powerups.

# Answer
> 1 votes
I think this question should still be closed and I'm just using this space to better explain the answer found here. Sorry, I haven't used Python in years, and only used it a little bit so this answer is not Python oriented at all.

With your paddle class, you would have something like this (which you probably already have):

```
Paddle {
    private int paddleWidth;

    public void setPaddleWidth(int aWidth) {
        paddleWidth = aWidth;
    }
    public int getPaddleWidth() { return paddleWidth;}

}

```

Then as an example powerup, you'd have something like:

```
PaddlePowerup implements Powerup {
    PowerupType type
    EffectType effect;

    public static void pickedUp(Paddle targetPaddle) {
        switch(effect) {
            case PowerupType.GROW:
                 targetPaddle.setPaddleWidth(targetPaddle.paddleWidth() * 2);
                 break;
            case PowerupType.SHRINK:
                 targetPaddle.setPaddleWidth(targetPaddle.paddleWidth() * 0.5f);
                 break;
            case PowerupType.INVISIBLE:
                 targetPaddle.setVisible(false);
                 break;
            ...
        }
    }
    public static void pickedUp(Ball targetBall) {
        switch(effect) {
            case PowerupType.INVISIBLE:
                 targetBall.setVisible(false);
                 break;
            case PowerupType.SLOW:
                 targetBall.setSpeed(targetBall.getSpeed() * 0.5f);
                 break;
            ...
        }
    }
}

```

The other answer doesn't go into how to do different power ups for different objects, like the ball, bricks or global parameters.

So when your paddle picks up a power up you could call something like this in your main game code (somewhere that has access to all your objects):

```
public void triggerPickup(Powerup powerup) {
    switch(powerup.type) {
        case PowerUpType.PaddlePowerup:
             pickedUp(playerPaddle);
        case PowerUpType.BallPowerup:
             pickedUp(playerBall);
        ...
    }
}

```

---
Tags: 2d, software-engineering, game-mechanics, python, pygame
---


# Question
Title: How to detect collisions between bullet and alien
I am designing a game for Android using Surface View. When a bullet hits any point on an alien it should blow the alien up. I wrote some code to detect collisions, but my code only triggers when my bullet hits the exact (x,y) coordinates of the alien. How do I write the collision-detection system so the alien will blow up wherever the bullet hit it?

# Answer
In most cases I was happy with measuring the distance between the center of the sprite and the center of the bullet. When it is small enough blow up the unit...preferably a greedy money-obsessed "human," not a good and green "alien!"

Pythagoras and his theorem are your friend...
> 1 votes

# Answer
You need to check if you bullet is touching any part of image, if image is rectangular you just check if bullet is inside rectangle. If your image is more complex then rectangle you need to do pixel perfect collision, that means go through all your image and check if your bullet hit some colored spot.
> 0 votes

---
Tags: android, collision-detection
---


# Question
Title: Collision detection with non-rectangular images
I'm creating a game and I need to detect collisions between a character and some parts of the environment. Since my character's frames are taken from a sprite sheet with a transparent background, I'm wondering how I should go about detecting collisions between a wall and my character only if the colliding parts are non-transparent in both images.

I thought about checking only if part of the rectangle the character is in touches the rectangle a tile is in and comparing the alpha channels, but then I have another choice to make... Either I test every single pixel against every single pixel in the other image and if one is true, I detect a collision. That would be terribly ineficient.

The other option would be to keep a x,y position of the leftmost, rightmost, etc. non-transparent pixel of each image and compare those instead. The problem with this one might be that, for instance, the character's hand could be above a tile (so it would be in a transparent zone of the tile) but a pixel that is not the rightmost could touch part of the tile without being detected. Another problem would be that in different frames, the rightmost, leftmost, etc. pixels might not be at the same position.

Should I not bother with that and just check the collisions on the rectangles? It would be simpler, but I'm afraid people.will feel that there are collisions sometimes that shouldn't happen.

# Answer
*I've talked about this a few times before (see related answers at the bottom) but I'll repeat myself.*

As you can imagine, checking every pixel against every other pixel would be very inefficient, even if you limited those pixels to the rectangle range that is actually intersecting. But like you mentioned, your second option also has its share of problems.

With that in mind, I'd like to drop two suggestions to solve your problem. The first one is just common practice. The one that really matters is the second:

==================================================

# Suggestion #1 - Check rectangles first

==================================================

This suggestion is pretty obvious. **Instead of always doing a pixel perfect collision check, start by checking if there's a rectangle-rectangle collision**:

* If there is, you'll still need to perform the pixel perfect collision check. In this case it ends up being a little more expensive because of the added rectangle-rectangle collision check.
* But if there isn't, you can return false and exit right there, because there's no chance of any pixels intersecting.

In practice you'll see a large performance gain from this, because the amount of tiles that are not colliding is probably a *lot* larger than those that are colliding.

==============================================

# Suggestion #2 - Use collision points

==============================================

Instead of checking every pixel in the environment tile against every pixel in the character sprite, **define a small number of collision points on your character, and only check against those points**. This is the approach used by classic Sonic games (see link at the end for more information).

Here's an example. Considering the following information:

1. *Tile Collision Mask*

Nothing special here, it's just a mask created from the opacity values of the tile texture.
2. *Character Collision Points*

Notice how there are 3 collision points at the bottom, 3 at the top, and 2 in the middle, one on each side. The advantage of having separate collision points is that you can use them for different tasks. For instance, the bottom collision points can be used to detect collisions with the floor, the middle collision points can be used to detect collisions with the walls, and the top collision points can be used to detect collisions with the ceiling.

There's also many other tricks that you can perform with this technique. For example, if only one of the bottom collision points is hitting the floor, you can change to an "out of balance" animation because the player must be near a ledge. Or by varying the height of the middle collision points, you can determine which types of slopes or stairs the character can climb.

Bottom line, with this approach you'll reduce from N x M pixel checks to N x 8 (with the example given) which is almost certainly a lot faster.

*You can also define different collision points for each frame of the animation. And by the way you can define a collision point simply as an X and Y offset from the character's origin.*

=========================================

# Related answers and resources

=========================================
> 18 votes

---
Tags: collision-detection, sprites, transparency
---


# Question
Title: Not getting desired results with SSAO implementation
After having implemented deferred rendering, I tried my luck with a SSAO implementation using this Tutorial. Unfortunately, I'm not getting anything that looks like SSAO, you can see my result below.

You can see there is some weird pattern forming and there is no occlusion shading where there needs to be (i.e. in between the objects and on the ground). The shaders I implemented follow:

```

#VS
#version 330 core

uniform mat4 invProjMatrix;

layout(location = 0) in vec3 in_Position;
layout(location = 2) in vec2 in_TexCoord;

noperspective out vec2 pass_TexCoord;
smooth out vec3 viewRay;

void main(void){
    pass_TexCoord = in_TexCoord;
    viewRay = (invProjMatrix * vec4(in_Position, 1.0)).xyz;
    gl_Position = vec4(in_Position, 1.0);
}

```

```

#FS
#version 330 core

uniform sampler2D DepthMap;
uniform sampler2D NormalMap;
uniform sampler2D noise;

uniform vec2 projAB;
uniform ivec3 noiseScale_kernelSize;
uniform vec3 kernel[16];
uniform float RADIUS;
uniform mat4 projectionMatrix;

noperspective in vec2 pass_TexCoord;
smooth in vec3 viewRay;

layout(location = 0) out float out_AO;

vec3 CalcPosition(void){
    float depth = texture(DepthMap, pass_TexCoord).r;
    float linearDepth = projAB.y / (depth - projAB.x);
    vec3 ray = normalize(viewRay);
    ray = ray / ray.z;
    return linearDepth * ray;
}

mat3 CalcRMatrix(vec3 normal, vec2 texcoord){
    ivec2 noiseScale = noiseScale_kernelSize.xy;
    vec3 rvec = texture(noise, texcoord * noiseScale).xyz;
    vec3 tangent = normalize(rvec - normal * dot(rvec, normal));
    vec3 bitangent = cross(normal, tangent);

    return mat3(tangent, bitangent, normal);
}

void main(void){

    vec2 TexCoord = pass_TexCoord;
    vec3 Position = CalcPosition();
    vec3 Normal = normalize(texture(NormalMap, TexCoord).xyz);

    mat3 RotationMatrix = CalcRMatrix(Normal, TexCoord);

    int kernelSize = noiseScale_kernelSize.z;

    float occlusion = 0.0;

    for(int i = 0; i < kernelSize; i++){
        // Get sample position
        vec3 sample = RotationMatrix * kernel[i];
        sample = sample * RADIUS + Position;
        // Project and bias sample position to get its texture coordinates
        vec4 offset = projectionMatrix * vec4(sample, 1.0);
        offset.xy /= offset.w;
        offset.xy = offset.xy * 0.5 + 0.5;
        // Get sample depth
        float sample_depth = texture(DepthMap, offset.xy).r;
        float linearDepth = projAB.y / (sample_depth - projAB.x);
        if(abs(Position.z - linearDepth ) < RADIUS){
            occlusion += (linearDepth <= sample.z) ? 1.0 : 0.0;
        }
    }
    out_AO = 1.0 - (occlusion / kernelSize);
}

```

I draw a full screen quad and pass Depth and Normal textures. Normals are in RGBA16F with the alpha channel reserved for the AO factor in the blur pass. I store depth in a non linear Depth buffer (32F) and recover the linear depth using:

```

float linearDepth = projAB.y / (depth - projAB.x);

```

where `projAB.y` is calculated as:

and `projAB.x` as:

These are derived from the glm::perspective(gluperspective) matrix. z\_n and z\_f are the near and far clip distance.

As described in the link I posted on the top, the method creates samples in a hemisphere with higher distribution close to the center. It then uses random vectors from a texture to rotate the hemisphere randomly around the Z direction and finally orients it along the normal at the given pixel. Since the result is noisy, a blur pass follows the SSAO pass.

Anyway, my position reconstruction doesn't seem to be wrong since I also tried doing the same but with the position passed from a texture instead of being reconstructed.

I also tried playing with the Radius, noise texture size and number of samples and with different kinds of texture formats, with no luck. For some reason when changing the Radius, nothing changes.

Does anyone have any suggestions? What could be going wrong?

# Answer
> 6 votes
I found the problem. It was a really stupid mistake, I didn't know you had to specify `glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);` to get the correct depth values and thus, I wasn't sampling the Depth values. Now I get a nice SSAO effect:

---
Tags: glsl, deferred-rendering, ssao
---


title: Creating a new instance, C#

text:
# Question
Title: Creating a new instance, C#
**EDIT:** I've added bits of my GameplayScreen class so that you can see how my ball and bats are initialized.

This sounds like a very n00b question, but bear with me here:

I'm trying to access the position of my **bat** (paddle) in my pong game and use it in my **ball** class. I'm doing this because I want a particle effect to go off at the point of contact where the ball hits the bat.

Each time the ball hits the bat, I receive an error stating that *I haven't created an instance of the bat*. I understand that I have to (or can use a static class), but I'm not sure of how to do so in this example.

I've included both my Bat and Ball classes.

```
public class Ball
{
     ....
    private bool hasHitBat;
    private AIBat aiBat;
    private Bat bat;
     ....

    /// <summary>
    /// Constructor for the ball
    /// </summary>
    public Ball(ContentManager contentManager, Vector2 ScreenSize)
    {
        moveSpeed = 15f;
        speed = 0;
        texture = contentManager.Load<Texture2D>(@"gfx/balls/redBall");
        direction = 0;
        size = new Rectangle(0, 0, texture.Width, texture.Height);
        resetPos = new Vector2(ScreenSize.X / 2, ScreenSize.Y / 2);
        position = resetPos;
        rand = new Random();
        isVisible = true;
        hasHitBat = false;

        // Everything to do with particles
        List<Texture2D> textures = new List<Texture2D>();
        textures.Add(contentManager.Load<Texture2D>(@"gfx/particle/circle"));
        textures.Add(contentManager.Load<Texture2D>(@"gfx/particle/star"));
        textures.Add(contentManager.Load<Texture2D>(@"gfx/particle/diamond"));
        particleEngine = new ParticleEngine(textures, new Vector2());
    }

    /// <summary>
    /// Checks for the collision between the bat and the ball. Sends ball in the appropriate
    /// direction
    /// </summary>
    public void BatHit(int block)
    {
        if (direction > Math.PI * 1.5f || direction < Math.PI * 0.5f)
        {
            hasHitBat = true;
            particleEngine.EmitterLocation = new Vector2(aiBat.Position.X, aiBat.Position.Y);
            switch (block)
            {
                case 1:
                    direction = MathHelper.ToRadians(200);
                    break;
                case 2:
                    direction = MathHelper.ToRadians(195);
                    break;
                ................
            }
        }
        else
        {
            hasHitBat = true;
            particleEngine.EmitterLocation = new Vector2(bat.Position.X, bat.Position.Y);
            switch (block)
            {
                case 1:
                    direction = MathHelper.ToRadians(310);
                    break;
                case 2:
                    direction = MathHelper.ToRadians(345);
                    break;
                ...............
            }
        }

        if (rand.Next(2) == 0)
        {
            direction += MathHelper.ToRadians(rand.Next(3));
        }
            else
        {
            direction -= MathHelper.ToRadians(rand.Next(3));
        }
        AudioManager.Instance.PlaySoundEffect("hit");
    }
 }

```

---

```
public class Bat
{

    /// <summary>
    /// Constructor for the bat
    /// </summary>
    public Bat(ContentManager contentManager, Vector2 screenSize, bool side)
    {
        moveSpeed = 7f;
        turbo = 15f;
        recharge = 100f;
        points = 0;
        interval = 5f;
        leftBat = contentManager.Load<Texture2D>(@"gfx/bats/batGrey");
        size = new Rectangle(0, 0, leftBat.Width, leftBat.Height);

        // True means left bat, false means right bat.
        if (side) Position = new Vector2(30, screenSize.Y / 2 - size.Height / 2);
        else Position = new Vector2(screenSize.X - 30, screenSize.Y / 2 - size.Height / 2);
        yHeight = (int)screenSize.Y;
    }

    /// <summary>
    /// Sets thedefault starting position for the bats
    /// </summary>
    /// <param name="position"></param>
    public void SetPosition(Vector2 position)
    {
        if (position.Y < 0)
        {
            position.Y = 0;
        }
        if (position.Y > yHeight - size.Height)
        {
            position.Y = yHeight - size.Height;
        }
        this.Position = position;
    }

    /// <summary>
    /// Checks for the current position of the bat
    /// </summary>
    public Vector2 GetPosition()
    {
        return Position;
    }

    /// <summary>
    /// Updates the position of the AI bat, in order to track the ball
    /// </summary>
    /// <param name="ball"></param>
    public virtual void UpdatePosition(Ball ball)
    {
        size.X = (int)Position.X;
        size.Y = (int)Position.Y;
    }

    /// <summary>
    /// Draws the bats
    /// </summary>
    public virtual void Draw(SpriteBatch batch)
    {
        batch.Draw(leftBat, size, Color.White);
    }

    }
}

```

---

```
Class GameplayScreen

   {
               protected void Initialize()
    {
        ........
        ball = new Ball(contentManager, new Vector2(ScreenManager.Game.GraphicsDevice.Viewport.TitleSafeArea.Width,
                             ScreenManager.Game.GraphicsDevice.Viewport.TitleSafeArea.Height));

        SetUpSingle(); // Sets up a single player game
        ......
 }

    /// <summary>
    /// Sets up a single player game, specifically the bats
    /// </summary>
    private void SetUpSingle()
    {
        rightBat = new AIBat(contentManager, new Vector2(ScreenManager.Game.GraphicsDevice.Viewport.TitleSafeArea.Width,
             ScreenManager.Game.GraphicsDevice.Viewport.TitleSafeArea.Height), false);
        leftBat = new Bat(contentManager, new Vector2(ScreenManager.Game.GraphicsDevice.Viewport.TitleSafeArea.Width,
            ScreenManager.Game.GraphicsDevice.Viewport.TitleSafeArea.Height), true);
    }

```

# Answer
> 4 votes
It sounds like you have your game working, which means you have an instance of bat and ball somewhere in your code (Game1.cs or its equivalent), I assume.

If you need your ball object to react to the bat object's properties, then you need the ball class to have a reference to the bat instance. You can do this in two ways:

1) Services.

2) Pass an object via a constructor, property, or method.

3) Do neither. Instead, handle your collision detection and particle effects outside of both of these classes. (recommended)

Here's an example of passing the already created bat object to the ball constructor, so that ball can then access bat's public properties and methods:

```
// Game1.cs

private Bat bat;
private Ball ball;

protected void LoadContent() {
    ...
    Bat bat = new Bat();          // create the bat
    Ball ball = new Ball( bat );  // create the ball, passing in the bat
    ...
}

```

Then in your Ball class:

```
// Ball.cs

private Bat bat;                  // this will hold the local reference to the bat

public Ball( Bat myBat ) {
    ...
    bat = myBat;                  // this assigns and instantiates the member bat
    ...                           // with myBat which was passed from the constructor
}

public override Update( GameTime gameTime ) {
    ...
    // now we can access the bat via the local private member, bat
    doSomethingWithBat( bat.Position );
    ...
}

```

Of course, I would recommend against having objects rely on each other. Instead, I would write another class or a few lines of code outside of those classes to detect the collision and play render your particle effect. Something like:

```
public override void Update( GameTime gameTime ) {
    ...
    if( Collision( ball, bat ) ) {
        ParticleManager.Play( Particle.BigBaddaBoom, ball.Position );
    }
    ...
}

```

The reason I would recommend this method is that it decouples your classes from each other making debugging simpler and your classes more re-usable. If you end up chaining your objects together, a simple modification of one class can have cascading effects on the rest of your code making what should be a simple change into a major code refactor.

---

Here's how you could modify your existing classes to pass your Bat object to your Ball object:

```
public class Ball
{
    ....
    private bool hasHitBat;
    private AIBat aiBat;
    private Bat bat;    // this will hold the reference to the player's bat
                        // that can be used throughout the rest of the class
    ....

    /// <summary>
    /// Constructor for the ball
    /// </summary>
    public Ball(ContentManager contentManager, Vector2 ScreenSize, Bat playerBat ) {
        bat = playerBat;
        ...
    }

```

Then in your GameplayScreen, you would have to flip some things around:

```
class GameplayScreen
{

    private Ball ball;
    private Bat leftBat;

    protected void Initialize()
    {
        ...
        SetUpSingle(); // Sets up a single player game

        ball = new Ball(
                   contentManager,
                   new Vector2(
                       ScreenManager.Game.GraphicsDevice.Viewport.TitleSafeArea.Width,
                       ScreenManager.Game.GraphicsDevice.Viewport.TitleSafeArea.Height),
                   leftBat, );
        ...
    }

```

Now as your GameplayScreen updates the leftBat object, you'll need to update the Ball object (to let it know about the changes to it's local bat object), and your ball will be able to react to the player's bat.

I still think it's easier to test for collisions inside your GameplayScreen.Update() method, but if you want to go down this route, that would be how you could do it.

# Answer
> 3 votes
I would remove the bat from your Ball class and change the BatHit method signature from:

```
public void BatHit(int block)

```

to

```
public void Hit(Bat bat, int block)

```

Your code then becomes

```
Bat bat = new Bat();
Ball ball = new Ball();
if (ball.Hit(bat))
{
    // Do something
}

```

# Answer
> 1 votes
It looks to me that you're not initializing bat or aiBat anywhere, which is what it's complaining about. Since they're defined as members of Ball, its going to be looking to those even if you have Bat and AIBat classes by those same names in another class.

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


title: Handling hitboxes

text:
# Question
Title: Handling hitboxes
So I have an issue that I'm laughing at myself about, because it really seems like it should be something that I should be able to figure out pretty quickly.

I am designing a 2D action platformer; I have a playable character, and a dummy 'punching bag' character for testing purposes that I've created. I've just gotten enough of both of them done that I can start prototyping and testing them in runtime.

Then I realized- neither of them have references of each other (intentionally so), so how do I check for hitboxes stored within my playable character from my dummy character?

Long story short, how do I make my dummy know when he's been punched by my hero?

# Answer
> 2 votes
You don't need them to have references to each other.

### Have a central hitbox system for your stage that does the work for them

Your hitbox system must have a list of all the hitboxes relevant to it - you'd generally have one hitbox system per world. How it finds out about its hitboxes is up to you, but the approach I take is (skipping all the detail) that every hitbox knows about the stage it's on, so it registers itself by calling: `this.Stage.HitboxSystem.Add(this)`

Once per update, this hitbox system goes through all the hitboxes known to it and lets them know if they're colliding with any other hitboxes (giving them whatever information is necessary, e.g. a reference to the other hitbox).

Next time your playable character or your "punching bag" need to know if they're touching anything, they've already been informed by the hitbox system and don't need to go check for themselves first.

---
Tags: xna, 2d, xna-4.0, platformer
---


title: Problem with AssetManager in libgdx

text:
# Question
Title: Problem with AssetManager in libgdx
I started using the asset manager, so I could use a loading screen. Everything is working fine, but when the app enters a pause state, it unloads every asset and when it loads the screen all the assets are gone. I debugged and I found that they are waiting to be loaded again, I commit an update to do it but nothing happened.

Am I missing something? (In the pause method, I don't unload anything)

# Answer
Most resources (like Texture, if its loaded from file) in libGDX are managed resources. If you load such resource using AssetManager, it takes care of it to be reloaded on resume, but you have to instruct your AssetManager to actually reload your resources. All you need to do is constantly call update() on resume until this method returns true, which indicates fully-loaded assets; or you can call finishLoading() to block you app till everything is loaded. You should read entry about libGDX architecture to get broader knowledge on how this framework works.

You may also find this link helpful.
> 2 votes

---
Tags: libgdx, assets, asset-management
---


title: Slopes in 2D Platformer

text:
# Question
Title: Slopes in 2D Platformer
I'm dealing with Slopes in a 2D platformer game I'm developing in XNA Game Studio. I was really tired of trying without success, until I found this post: 45° Slopes in a Tile based 2D platformer, and I solved part of the problem with the bummzack answer.

Now I'm dealing with 2 more problems:

1) Inverted slopes:

The post says:

*If you're only dealing with 45 degree angles, then it gets even simpler:*

***y1 = y + (x1 - x)***

*If the slope is the other way round, it's:*

***y1 = y + (v - (x1 - x))***

My question is, what if I'm dealing with slopes with less than 45 degree angles? Does ***y1 = y + (v - (x1 - x))*** work?

2) Going down the slope:

I can't find a better way to handle the "going down through the slope" situation, considering that my player can accelerate its velocity.

Edit: I was about to post a image but I guess I need to have more reputation he he he... What I'm trying to say with "going down" is like walking towards the opposite direction, assuming that if you are walking to the right, you are incrementing your Y position because you are climbing the slope, but if you are walking to the left, you are decrementing your Y position.

# Answer
> 4 votes
What you want to do is travel over that line and project the player's position onto the y-axis of the slope.

That sounds complicated, but it's alright.

Suppose we define a line as being between two points: `p0` and `p1`. We can define the slope of the line as `p1 - p0`. What we need to do is take the `x` of the player's position and plug it into our line equation to get its `y` position.

In code:

```
if (
    obj_player.x > obj_slope.GetStart().x &&
    obj_player.x < obj_slope.GetEnd().x
)
{
    // first we get the difference between the points
    tb::Vec2 slope = obj_slope.GetEnd() - obj_slope.GetStart();

    // to calculate the percentage of how far the player
    // is on the slope, subtract the start position
    // and divide by the horizontal slope
    float percentage = (obj_player.x - obj_slope.GetStart().x) / slope.x;

    // multiplying the percentage by the vertical slope gives us a value for y
    obj_player.y = percentage * slope.y;
}

```

Obviously this won't solve *all* your problems. You'll still need to think about the following:

* What happens when the player "enters" the slope?
* What happens when she wants to jump while on a slope?
* What happens when she lands on a slope?

---
Tags: xna, 2d, platformer
---


# Question
Title: Transform 3d viewport vector to 2d vector
I am playing around with 3d transformations and came along an issue.

I have a 3d vector already within the viewport and need to transform it to a 2d vector. (let's say my screen is 10x10)

Does that just straight works like regualar transformation or is something different here?

i.e.: I have the vector a = (2, 1, 0) within the viewport and want the 2d vector.

Does that works like this and if yes how do I handle the "0" within the 3rd component?

# Answer
If you have a **point** in 3D space you can multiply it by the view and then projection matrix to get the screen coordinate. This is a preferable method since it allows for different screens and view parameters. The example in the link x = x / z won't usually work since it relies on a very specific view frustum. It might be a good approximation for some system.

The issue with just multiplying with the view and then projection matrix is that you can loose magnitude in your vector which might not be what you want. This is because the camera isn't necessarily centered on the world origin.

So a point in 3D space of (10, 10, 0) might come out in screen space as (5, 5) instead of the expected (10, 10) because of the camera position. Since it's just a point we want then it's fine, but if you were working out how a vector for velocity will impact a 2D object, then this is obviously bad.

Finally, transforming from a 3D to a 2D coordinate system isn't the same as translating from world space to screen space which seems to be what you are asking. Going from world to screen requires knowledge of the view eye (camera) and the screen. Going from 3D to 2D is a different transformation which involves calculating an objects projection onto a plane. (I think an orthographic projection matrix might give an easy way to do this though, as I can't remember how you actually do it).
> 1 votes

---
Tags: 2d, 3d, vector, transformation
---


# Question
Title: Realistic planetary terrain generation with weights
I need terrain generation for a planet. The planet will be divided up into several hundred hexes, and I need it to be realistic and based on weights. I have dabbled in terrain generation before, but nothing like this. So I figure it would be a good idea to ask the community for answers, recommended articles or the like.

By realistic, I mean not just random hexes, but continent shaped things with a few islands. More desert around the equator and more ice around the poles.

I also have two weights I need to base it around: ice percentage and water percentage. That means that around XX% of the planet will need to be water.

Does anyone have any advice or places to start? Generating arbitrary terrain is easy, but something a bit more "organic" like this seems rather difficult.

It also needs to be seamless. Should be obvious since it's a planet, but no harm in pointing it out.

# Answer
As with most terrain generation, noise functions are your friend - Perlin and/or simplex noise in particular. I've implemented some planetary terrain generation algorithms and although they are in 2d, the resulting height / "texture" map could be projected to a sphere rather easily. I assume conversion to hex format is not an issue either.

My technique has been creating multiple noise layers, e.g. temperature and humidity. Temperature is fused with a latitude coordinate, in order to make the equator more hot and poles cold, while the noise makes sure it's not a simple gradient. The final terrain type is selected by rules like "if hot and not humid then pick desert". You can see my JavaScript implementation of this here: https://github.com/tapio/infiniverse/blob/master/js/universe/planet-aerial.js

As for the water percentage, you can just adjust the water level height as noise functions tend to have a constant average. Another option is to apply an exponent filter (useful also when generating clouds, see my implementation here).

Another way to generate spherical terrain that came into mind (haven't tested) is to use 3d noise and sample it from a surface of a sphere, using the resulting value as the ground height at that point. You can then weight that according to amount of water on planet and the latitude coordinate.

I'll end with a link to one practical implementation of 3d planetary terrain generation: http://libnoise.sourceforge.net/tutorials/tutorial8.html
> 7 votes

---
Tags: procedural-generation, terrain, planet
---


title: Top down water view, cocos2d

text:
# Question
Title: Top down water view, cocos2d
Has anyone successfully created a top down view of a stream/river? I need to also work out how to make it look like a boat is cutting through the water.

# Answer
> 1 votes
This might be what you're looking for to simulate the surface of water.

http://thebackfiregames.wordpress.com/2012/01/16/ripples/

# Answer
> 0 votes
You would need to animate particles in a wave fashion, so that each particle's velocity is affected by - 1. wave motion over time 2. the opposite of the boat's velocity ... and move each particle over time.

---
Tags: cocos2d-iphone, cocos2d, particles, water
---


title: Tetris : Effective rotation

text:
# Question
Title: Tetris : Effective rotation
I rotate each piece by rotation formula. More detail, because rotation angle is 90 so :

```
xNew = y;

yNew = -x;

```

But my method has met two problems :

**1) Out of box :** each type of pieces is fit in square 4x4. (0,0 at under left) But by this rotation, at some case they will out of this box. For example, there is a point with coordinate (5,6) So, please help me how to fit these coordinate into 4x4 box again, or give me another formula for this.

**2) at I case :** (4 squares at same row or same column), just has two rotations case. but in method above, they still has 4 pieces. So, how to prevent this.

Thanks :)

# Answer
You could just store the rotations in an array like you'd store your blocks, four for each block type, then just iterate over them. That way you don't have to deal with the mess you've described.
> 13 votes

# Answer
I usually use a rotation matrix to deal with rotation of the pieces. Since the rotation is always +/-90 degrees, you can create a rotation matrix with the fixed values in them and then multiply it by the current positions of each piece when rotating.

To deal with the fact that certain pieces have different numbers of rotations, I usually store a variable that says how many different rotations each piece has.
> 3 votes

# Answer
**Copying my answer to your closed question on SO: https://stackoverflow.com/questions/11106496/tetris-issues-when-rotate-pieces/**

The Tetris board is a grid layout. A very simple way of understanding is that a Tetris piece is just a set number of squares that are 'filled'. In a boolean sense, a piece can be viewed as `0`, or unfilled, or `1`, filled. Using a grid (or tile-based) approach will prevent your blocks from ever going out of bounds and as an added bonus also simplifies collision code when you reach a bottom-collision.

**Pseudo-code**: You can do a check `if (!grid[x][y]) block.move(direction)` where `grid[x][y]` is a space you want to move into and `block.move(direction)` is an arbitrary function that adjusts your piece and map by one grid space in whatever direction is specified. In this sense, your game loop could also use `block.move('down')` to drop the piece incrementally and `else block.stop(), game.generateBlock()` for the next piece.

Using the grid method, you can easily check to see if your rotated piece will be out-of-bounds as `if(x < 0 || x > gridWidth) block.move(direction)`, in which `direction` is the direction opposite of the way it would had moved out-of-bounds.

Continuing with the grid-based example, your pieces are really just a pattern of on/off as well and their rotation is displayed as so:

```
  ▇    ▇        ▇ ▇    ▇ ▇ ▇
  ▇ or ▇ ▇ ▇ or ▇   or     ▇
▇ ▇             ▇

```

What is illustrated just by this rudimentary artwork is that the pieces don't rotate around a central point due to the often rectangular pieces. The patterns can be stored in their boolean state easily enough, however, and you can just track which 'position' it is in and write your code to test it regardless of the orientation.

Since each piece has a finite number of patterns it can be in (4 maximum) and it is probably in your best interest to simply hard-code them in. This answer provides some code you may find inspiring: https://stackoverflow.com/a/8131337/571506

I highly recommend doing the research and learning a little linear algebra with these simple variables if there's even the slightest chance you'll move into 3D game programming. Since each piece can be stored as a matrix, you can apply simple transformations to the base 'piece matrix' to get the new pattern. This can be faked easily enough, or you can go all-out. I highly recommend doing the research and learning a little linear algebra with these simple variables if there's even the slightest chance you'll move into 3D game programming. For algorithms, check out this question: https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array

Tetris is an extremely well-documented game and can add a lot of skills to your 'toolbox'. Try to figure as much of it out using provided paradigms as possible while doing majority of the programming by hand and you'll find it a great to benefit in the long run.
> 3 votes

---
Tags: rotation
---


# Question
Title: Loading class instance from XML with Texture2D
I'm having trouble with XML and XNA. I want to be able to load weapon settings through XML to make my weapons easier to make and to have less code in the actual project file. So I started out making a basic XML document, something to just assign variables with. But no matter what I changed it gave me a new error every time. The code below gives me a "XML element 'Tag' not found", I added and it started to say the variables weren't found.

What I wanted to do in the XML file as well, was load a texture for the file too. So I created a static class to hold my texture values, then in the Texture tag of my XML document I would set it to that instance too. I think that's were the problems are occuring because that's where the "XML element 'Tag' not found" error is pointing me too.

My XML document:

```
 <XnaContent>
   <Asset Type="ConversationEngine.Weapon">
    <weaponStrength>0</weaponStrength>
    <damageModifiers>0</damageModifiers>
    <speed>0</speed>
    <magicDefense>0</magicDefense>
    <description>0</description>
    <identifier>0</identifier>
    <weaponTexture>LoadWeaponTextures.ironSword</weaponTexture>
   </Asset>
 </XnaContent>

```

My Class to load the weapon XML:

```
public class Weapon
{
    public int weaponStrength;
    public int damageModifiers;
    public int speed;
    public int magicDefense;
    public string description;
    public string identifier;
    public Texture2D weaponTexture;
}

public static class LoadWeaponXML
{
    static Weapon Weapons;

    public static Weapon WeaponLoad(ContentManager content, int id)
    {
        Weapons = content.Load<Weapon>(@"Weapons/" + id);

        return Weapons;
    }
}

public static class LoadWeaponTextures
{
    public static Texture2D ironSword;
    public static void TextureLoad(ContentManager content)
    {
        ironSword = content.Load<Texture2D>("Sword");
    }
}

```

I'm not entirely sure if you can load textures through XML, but any help would be greatly appreciated.

# Answer
As Blau said, just store some kind of reference to where the texture is. I recommend using a different class for storing texture info, and referencing that by an Id. In this case, you'll have 2 XML files:

```
<XnaContent>
  <Asset Type="ConversationEngine.Weapon">
    <weaponStrength>0</weaponStrength>
    <damageModifiers>0</damageModifiers>
    <speed>0</speed>
    <magicDefense>0</magicDefense>
    <description>0</description>
    <identifier>0</identifier>
    <TextureId>1</TextureId>
  </Asset>
</XnaContent>

```

And

```
<XnaContent>
  <Asset Type="ConversationEngine.Texture">
    <Id>1</Id>
    <Path>Textures/weapon01</Path>
    <Frames>4</Frames>
    <FirstFrame>0 0 32 32</FirstFrame>
  </Asset>
</XnaContent>

```

This way you can easily manage your texture data in case you want to implement animated textures for example. This is really helpful if you're going to have more classes that use textures (armor, weapon, monster etc.) with different sizes and / or number of animation frames, transparency etc.

Then you'll need a generic class that handles texture loading / drawing. This will take a Weapon (or Monster, Armor...) instance, and create a new instance of the Texture class with the parameters read from the XML, identified by the Weapon.TextureId property.

This might seem to be too much work at the beginning, but as your engine gets more and more features, it will save you many days of work (and refactoring). My simple, 2D sprite engine is about 60% done, and my Sprite (~ Texture) class has more than 10 properties. But with the architecture I explained, it's really easy to implement new effects for every and any game object that is displayed as a sprite.

Unfortunately I'm not at home right now, so can't post the relevant parts of my source code. Just let me know if you need them, and I'll edit the post.

Edit: You should use the built-in serializer to create your XML templates, at least until you're familiar with XNA's content manager and the XML representation of certain types.
> 1 votes

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


# Question
Title: Provide A Scrolling "Camera" View Over A 2D Game Map
I'm in the process of attempting to create a 2D MMO type game with Kryonet and some basic sprites, mostly for my own learning. I have the back end set up great (By my standards) and I'm moving on to actually getting some things drawn onto the map.

I cannot for the life of me figure out a solid way to have a "Camera" follow a player around a large area. The view pane for the game is 640 x 480 pixels, and each tile is 32x32 pixels (Thats 20 tiles wide and 15 high for the viewpane)

I have tried a couple things to do this, but they did not seem to work out so well. I had a JScrollPane with 9 "Viewpane"-sized canvases in it, and tried to have the JScrollPane move in accordance with the player. The issue came when I reached the end of the JScrollPane. I tried to "Flip" canvases, sending the canvas currrently drawing the player to the middle of the 9 and load the corresponding maps onto the other ones. It was slow and worked poorly.

I'm looking for any advice or previous experience with this; any ideas?

Thank you!

---

***Edit and Clarification:*** I did not mean to mention Kryonet, I was merely providing peripheral information in case there was something that would help which I could not foresee.

Instead of having an array of 9 canvases, why not just have one large canvas loading a large map every once in a while? I'm willing to have "load times" where as with the canvas array I would have none (in theory) to give the user a smooth experience.

I could just change the size and location of the map with a modified setBounds() call on the canvas in a layered pane (layered because I have hidden swing items, like inventories and stuff)

I'll try it out and post here how it goes for people asking the same question.

# Answer
I had this exact same scroll pane problem in an early prototype of a 2D platform game.

My setup was:

* JFrame, containing
    + JScrollPane, containing
        - JPanel (\<- this is where I draw my level)

The frame has a fixed size (800x600, or whatever), likewise with the scroll pane. The JPanel has a size == the size of the level.

To scroll, don't mess with scroll pane movement; as you've noticed, it's jumpy and looks really bad (double buffering--or lack thereof--has nothing to do with it). Instead, when you render your JPanel, use `Graphics.translate` (http://docs.oracle.com/javase/6/docs/api/java/awt/Graphics.html#translate(int, int)) to shift the origin of your coordinates. You'll have to calculate the exact x and y translate values based on the movement of the player in relation to the level (taking into account the edges of the level, of course).

In summary:

Your initial intuition makes sense: when the player moves, move the view of the scroll pane around the level. This is what we generally expected from most programs we use that have some scrolling functionality. However, the better (and smoother) solution is the opposite: move the level, not the view.

To put it another way: If your player moves to the right, don't scroll to the right--just move the level to the left. Think about it that way.
> 1 votes

# Answer
I can't help with Kryonet-related stuff, but as far as I know Kryonet just handles the networking so you are on your own for the game-enine part, right? Also your question doesn't seem Kryonet-specific.

You're talking about a JScrollPane and canvas, I'm assuming you got a canvas inside a Frame window of some sort and that you can do pretty much what you want with those.

On the canvas you render the tiles to compose the whole map (or maybe render them all to a single macro-texture and store it to have less rendering calls).

To begin with you would need a timer to get time-based input (including scrolling). You could also want the amount of scrolling be related to the speed of the character being followed.

An easy way to get the scrolling done (and the character movement) is to store the character's logical position on the server-side and let every player see his own character graphic surrounding.

That means that only the coordinates of the characters on the server will change. On the client, it's the map the moves around.

After getting the input to start the scrolling and the direction to scroll (2D game, so N/S/W/E), just translate all the tiles (or the macro texture) in the opposite direction, where the time-slice received from a timer defines how much to scroll.

After that, update the logical position of the character on the server, and that's basically done.

Since you are also saying that it's slow (client-side I guess), you should create as many textures as possibile before starting the actual playing.

Also, as the character moves around, you could try to create a 'buffer' of tiles on the client, preloading some extra tiles to cover a wider area around the character as it moves around and discarding (only if needed to free some memory) the ones that become too far to be useful.

That way you will alsway have a 'safe area' to move inside without needing any new loading. Also reusing the same textures in patterns is a good thing to do.

That should cover the map scrolling in a basic way.
> 0 votes

---
Tags: 2d, java, graphics, maps
---


title: Moving Character in C# XNA Not working

text:
# Question
Title: Moving Character in C# XNA Not working
I'm having trouble trying to get my character to move for a game I'm making in my sparetime for the Xbox. However, I can't seem to figure out what I'm doing wrong , and I'm not even sure if I'm doing it right. I've tried googling tutorials on this but I haven't found any helpful ones. Mainly, ones on 3d rotation on the XNA creators club website.

My question is : How can I get the character to walk towards the right in the MoveInput() function? What am I doing wrong? Did I code it wrong?

The problem is : The player isn't moving. I think the MoveInput() class isn't working.

Here's my code from my character class :

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Jumping
{
class Character
{
    Texture2D texture;
    Vector2 position;
    Vector2 velocity;
    int velocityXspeed = 2;
    bool jumping;

    public Character(Texture2D newTexture, Vector2 newPosition)
    {
        texture = newTexture;
        position = newPosition;
        jumping = true;
    }
    public void Update(GameTime gameTime)
    {
        JumpInput();
        MoveInput();
    }
    private void MoveInput()
    {
        //Move Character right
        GamePadState gamePad1 = GamePad.GetState(PlayerIndex.One);
        velocity.X = velocity.X + (velocityXspeed * gamePad1.ThumbSticks.Right.X);
    }

    private void JumpInput()
    {
        position += velocity;

        if (GamePad.GetState(PlayerIndex.One).Buttons.A == ButtonState.Pressed && jumping == false)
        {
            position.Y -= 1f;
            velocity.Y = -5f;
            jumping = true;
        }

        if (jumping == true)
        {
            float i = 1.6f;
            velocity.Y += 0.15f * i;
        }

        if (position.Y + texture.Height >= 1000)
            jumping = false;

        if (jumping == false)
            velocity.Y = 0f;
    }
    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, position, Color.White);
    }
}

```

}

# Answer
Though you haven't told us what the problem is. I can see that you never initialize your velocity variable.

```
Vector2 velocity = new Vector2(0,0);

```
> 4 votes

---
Tags: xna, c#, xbox, xbox-controller
---


# Question
Title: OpenGL 2.1+ Render with data returned form assimp library
I have just read this tutorial about how to load a 3D model file. Its render routine uses a `recursive_render` function to scan all nodes.

**My question:**

1. What does a `aiNode` struct store?
2. What the difference between this method and above method:

```
for (int i=0; i < scene->mNumMesh; ++i) {
   draw scene->mMeshes[i];
}

```

# Answer
> 1 votes
1) The aiNode struct is defined in the Assimp library. **Here** you can find it its definition on the official documentation:

```
Public Attributes
aiNode **       mChildren       // The child nodes of this node.
unsigned int *  mMeshes         // The meshes of this node.
aiString        mName           // The name of the node.
unsigned int    mNumChildren    // The number of child nodes of this node.
unsigned int    mNumMeshes      // The number of meshes of this node.
aiNode *        mParent         // Parent node.
aiMatrix4x4     mTransformation // The transformation relative to the node's parent.

```

2) I don't know what is the difference between "your method" and `recursive_render`, but looks like you are missing a lot of information (childs, etc). I'd have a closer look to `recursive_render`

---
Tags: opengl, c, assimp
---


# Question
Title: Create a rectangle struct to be rotated and have a .Intersects() function
In my XNA program, I am trying to swing a sword. The sword starts at an angle of 180 degrees, then rotates (clockwise) to an angle of 90 degrees.

The Rectangle struct that XNA provides,

```
Rectangle mAttackBox = new Rectangle(int x, int y, int width, int height);

```

However, this struct has two problems:

1. Holds position and size in Integers, not Floats
2. Cannot be rotated

I was hoping someone could help me in either telling me that i'm wrong and the Rectangle can be used for both these methods, or can lead me down the right path for rotating a rectangle.

I know how to create a Struct. I believe that I can make methods like classes. I can determine the 4 vertices of a 2D rectangle by calculating out the x,y of the other 3 given the length, width. I'm sure theres a Matrix class I can use to multiply each point against a Rotation matrix.

But once i have my 4 vertices, I got two other problems:

* How do I test other rectangles against it? How does .Intersects() work for the rectangle struct?
* Is this even the fastest way to do it? I'd be constantly doing matrix multiplication, wouldnt that slow things down?

# Answer
First you want to create the matrix transformation that will rotate the rectangle.

```
Matrix transform =
Matrix.CreateTranslation(new Vector3(-pivot, 0.0f)) *
Matrix.CreateRotationZ(angle) *
Matrix.CreateTranslation(new Vector3(position, 0.0f));

```

To calculate the rotated rectangle:

```
public static Rectangle CalculateBoundingRectangle(Rectangle rectangle,
                                                   Matrix transform)
{
    // Get all four corners in local space
    Vector2 leftTop = new Vector2(rectangle.Left, rectangle.Top);
    Vector2 rightTop = new Vector2(rectangle.Right, rectangle.Top);
    Vector2 leftBottom = new Vector2(rectangle.Left, rectangle.Bottom);
    Vector2 rightBottom = new Vector2(rectangle.Right, rectangle.Bottom);

    // Transform all four corners into work space
    Vector2.Transform(ref leftTop, ref transform, out leftTop);
    Vector2.Transform(ref rightTop, ref transform, out rightTop);
    Vector2.Transform(ref leftBottom, ref transform, out leftBottom);
    Vector2.Transform(ref rightBottom, ref transform, out rightBottom);

    // Find the minimum and maximum extents of the rectangle in world space
    Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop),
                              Vector2.Min(leftBottom, rightBottom));
    Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop),
                              Vector2.Max(leftBottom, rightBottom));

    // Return that as a rectangle
    return new Rectangle((int)min.X, (int)min.Y,
                         (int)(max.X - min.X), (int)(max.Y - min.Y));
}

```

Just use Rectangle.Intersects to see if it intersects with another rectangle. Stole this code from XNA transformed collision tutorial. http://create.msdn.com/en-US/education/catalog/tutorial/collision\_2d\_perpixel\_transformed
> 2 votes

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


title: Action button: only true once per press

text:
# Question
Title: Action button: only true once per press
I'm using SFML2.0 and am trying to make a wrapper class for my controller/joystick. I read all the input data from my controller and send it off to my controllable object.

I want to have two types of buttons per button press, one that is continues(true false state ) and one that is an action and is set to false after the next frame update.

Here is an example of how I set my button A to true or false with the SFML api. Whereas **data** is my struct of buttons, and **A** holds my true/false state every update.

```
data.A = sf::Joystick::isButtonPressed(i,st::input::A);

```

But I've also added "data.actionA" which represents the one time action state.

Basically what I want is for **actionA** to be set false after the update its been set to true. I'm trying to keep track of the previous state. But I seem to fall into this loop where it toggles between true and false every update.

Anyone an idea?

# Answer
Here's some pseudo code for you to try

```
// This here is a global variable.
...
    bool wasButtonPressed = false;
...

// This here is your function.
...
    bool isButtonPressed = sf::Joystick::isButtonPressed(i,st::input::A);

    // Check if the key was pressed since last frame, aka KeyPressed.
    if(isButtonPressed && !wasButtonPressed)
        someFunction();

    // Check if the key was held since last frame, aka KeyHeld.
    if(isButtonPressed && wasButtonPressed)
        someFunction();

    // Check if the key was released since last frame, aka KeyReleased.
    if(!isButtonPressed && wasButtonPressed)
        someFunction();

    wasButtonPressed = isButtonPressed;
...

```

We store the previous state, so we know how the key has changed since the last frame.
> 3 votes

# Answer
My solution:

```
data.actionA = data.A = sf::Joystick::isButtonPressed(i,st::input::A);
if(prev.A) data.actionA = false;

```

First I always set the actionA to the value of the button state. Then I check if the previous state of A is true. If so we negate the value.
> 0 votes

---
Tags: c++, input, sfml, controllers
---


# Question
Title: Position Reconstruction from Depth by inverting Perspective Projection
I had some trouble reconstructing position from depth sampled from the depth buffer. I use the equivalent of gluPerspective in GLM. The code in GLM is:

```

template
GLM_FUNC_QUALIFIER detail::tmat4x4 perspective
(
    valType const & fovy,
    valType const & aspect,
    valType const & zNear,
    valType const & zFar
)
{
    valType range = tan(radians(fovy / valType(2))) * zNear;
    valType left = -range * aspect;
    valType right = range * aspect;
    valType bottom = -range;
    valType top = range;

    detail::tmat4x4 Result(valType(0));
    Result[0][0] = (valType(2) * zNear) / (right - left);
    Result[1][2] = (valType(2) * zNear) / (top - bottom);
    Result[2][3] = - (zFar + zNear) / (zFar - zNear);
    Result[2][4] = - valType(1);
    Result[3][5] = - (valType(2) * zFar * zNear) / (zFar - zNear);
    return Result;
}

```

There doesn't seem to be any errors in the code. So I tried to invert the projection, the formula for the z and w coordinates after projection are:

and dividing z' with w' gives the post-projective depth (which lies in the depth buffer), so I need to solve for z, which finally gives:

Now, the problem is I don't get the correct position (I have compared the one reconstructed with a rendered position). I then tried using the respective formula I get by doing the same for this Matrix. The corresponding formula is:

For some reason, using the above formula gives me the correct position. I really don't understand why this is the case. Have I done something wrong? Could someone enlighten me please?

# Answer
> 2 votes
I believe the difference between the two stems from considering the post-projective (NDC) z range to be \[-1, 1\] (in your first formula) and \[0, 1\] (in your second). OpenGL uses the former while D3D uses the latter. It's strictly a matter of convention - in OpenGL, of course, the depth buffer range eventually ends up being \[0, 1\] as well, but the NDC space is throught of as \[-1, 1\] along all three axes and the conversion to \[0, 1\] is part of the viewport transformation. In D3D, the NDC space is thought of as \[-1, 1\] in XY and \[0, 1\] in Z, with the viewport transformation not doing anything to Z.

When you sample the depth buffer, you get back a result in \[0, 1\], so to unproject it back to world space you have to use a D3D-style matrix. This is equivalent to aborbing the Z part of OpenGL's viewport transformation into the projection matrix.

---
Tags: mathematics, depth-buffer, perspective
---


# Question
Title: What advantages does DirectX 11 have over DirectX 10?
What advantages does DirectX 11 have over DirectX 10? Most of the new features seemed to be for directcompute from what I can tell, and how much more are you limiting your market by if you use DX11 compared to DX10 (assuming you don't add DX10 support).

# Answer
You should usually prefer to use the D3D11 *API*, because it introduced downlevel feature level support that allows you to target 9, 10 or 11 level features using the same (D3D11) API. This means cleaner, more compact code so long as you don't have to support XP (and thus need to use the actual D3D9 API as well).

If you choose to require D3D11-level features, however, you will be limiting your market -- it's impossible to say by exactly how much in a fashion that is not overly time-sensitive, however, because market penetration will naturally change over time.

The primary advantages of the D3D11-level feature set are:

* Separation of device and context, allowing for better concurrency support.
* Compute, hull and domain shaders.
* Shader model 5.0 and dynamic shader linkage.
* WARP.

You may find this page, detailing the migration notes from D3D10 to D3D11, useful as a basis for comparision of more minor feature details.
> 11 votes

# Answer
One of the major benefits is the clear separation of the *device* and the *context*

The device is synchronized for use in arbitrary threads and is used for maintenance tasks like creating resources, while a context is tied to a particular thread.

There's two flavors of context, the immediate context which is tied to the GUI thread, and the deferred contexts, which may be used to queue draw commands and resource updates for later execution in the immediate context, somewhat akin to the display lists of OpenGL.

This separation has benefits like being able to do write-only discards and uploads of resources in streaming threads without hitching the rendering of the main thread. In these many-core days, being able to spread the load grows more and more important.
> 4 votes

---
Tags: directx, directx11, directx10
---


title: Circular motion on low powered hardware

text:
# Question
Title: Circular motion on low powered hardware
I was thinking about platforms and enemies moving in circles in old 2D games, and I was wondering how that was done. I understand parametric equations, and it's trivial to use sin and cos to do it, but could an NES or SNES make real time trig calls? I admit heavy ignorance, but I thought those were expensive operations. Is there some clever way to calculate that motion more cheaply?

I've been working on deriving an algorithm from trig sum identities that would only use precalculated trig, but that seems convoluted.

# Answer
On hardware such as you are describing, a common solution to the general case is to simply produce a look-up table for the trigonometry functions one was interested in, sometimes in conjunction with fixed-point representations for values.

The potential issue with this technique is that it consumes memory space, although you can downplay this by settling for a lower resolution of data in your table or by taking advantage of the periodic nature of some functions to store less data and mirror it at runtime.

However, for specifically traversing circles -- either to rasterize them or to move something along one, a variation of Bresenham's line algorithm can be employed. Bresenham's actual algorithm, of course, is also useful for traversing lines that are not in the eight "primary" directions quite cheaply.
> 14 votes

# Answer
There's a variation of Bresenham's algorithm by James Frith, which should be even faster since it completely eliminates multiplication. It doesn't need any lookup table to achieve this, although one could store the results in a table if the radius stays constant. Since both Bresenham's and Frith's algorithm use 8-fold symmetry, this lookup table would be relatively short.

```
// FCircle.c - Draws a circle using Frith's algorithm.
// Copyright (c) 1996  James E. Frith - All Rights Reserved.
// Email:  jfrith@compumedia.com

typedef unsigned char   uchar;
typedef unsigned int    uint;

extern void SetPixel(uint x, uint y, uchar color);

// FCircle --------------------------------------------
// Draws a circle using Frith's Algorithm.

void FCircle(int x, int y, int radius, uchar color)
{
  int balance, xoff, yoff;

  xoff = 0;
  yoff = radius;
  balance = -radius;

  do {
    SetPixel(x+xoff, y+yoff, color);
    SetPixel(x-xoff, y+yoff, color);
    SetPixel(x-xoff, y-yoff, color);
    SetPixel(x+xoff, y-yoff, color);
    SetPixel(x+yoff, y+xoff, color);
    SetPixel(x-yoff, y+xoff, color);
    SetPixel(x-yoff, y-xoff, color);
    SetPixel(x+yoff, y-xoff, color);

    balance += xoff++;
    if ((balance += xoff) >= 0)
        balance -= --yoff * 2;

  } while (xoff <= yoff);
} // FCircle //

```
> 9 votes

# Answer
You can also use an approximated version of trig functions using Taylor Expansions http://en.wikipedia.org/wiki/Taylor\_series

For example, you can have a reasonable approximation of sine using it's first four taylor series terms
> 2 votes

# Answer
One awesome algorithm to travel uniformly over a circle is the Goertzel algorithm. It requires only 2 multiplications and 2 additions per step, no lookup table, and a very minimal state (4 numbers).

First define some constants, possibly hardcoded, based on the required step size (in this case, 2π/64):

```
float const step = 2.f * M_PI / 64;
float const s = sin(step);
float const c = cos(step);
float const m = 2.f * c;

```

The algorithm uses 4 numbers as its state, initialised like this:

```
float t[4] = { s, c, 2.f * s * c, 1.f - 2.f * s * s };

```

And finally the main loop:

```
for (int i = 0; ; i++)
{
    float x = m * t[2] - t[0];
    float y = m * t[3] - t[1];
    t[0] = t[2]; t[1] = t[3]; t[2] = x; t[3] = y;
    printf("%f %f\n", x, y);
}

```

It can then go forever. Here are the first 50 points:

The algorithm can of course work on fixed point hardware. The clear win against Bresenham is the constant speed over the circle.
> 2 votes

---
Tags: algorithm
---


# Question
Title: What are examples of games with "minimalist" models/art assets
When teaching game development, my student's obsess about building realistic or complex art/models/animation. And spending wayyy to much time trying to get accurate collision detection between two 3D models \[despite my best efforts\]

However I would like them to spend more time thinking about developing the game mechanics, interaction and game play.

I'm looking for some games where the visuals are simple but have good game play.

Things I am thinking about are Cubes' vs Spheres or Impossible Game.

What are more examples of visually simple (preferably 3D) games to help inspire my students?

# Answer
Minecraft (doh!)

Darwinia

As a side note, most of the indie hits don't apply IMHO. Braid, Fez, Limbo et al. focus on visual appeal as one of the main selling points. Even if the graphics are not ment to be realistic or visualy complex, they take a major part in the development cycle, while f.e Minecraft values function over form.
> 6 votes

# Answer
The best game that comes to mind is

http://www.youtube.com/watch?v=YDaa3Cq6c7M

Thomas was alone^ : It's an amazing minimalist game that really shows that graphics don't matter and that gameplay is king.

I'm also working on my own minimalist game at the moment for the Xbox 360 for XBLA, and here's a list of other cool minimalist games.

http://www.youtube.com/watch?v=Wu6iXBYkGPY

* ^Everyday the same dream is extremely minimalist and well done. 2d
* Canabalt is somewhat minimalist. 2d / 2.5d perspective
* Super Meat boy is somewhat minimalist. 2d
* Grey - Flash Game on Kongregate 2d
* One and one story - somewhat minimalist. 2d
* The Floor is Jelly - very minimalist. 2d
* Wonderputt - minimalist in some aspect. 2.5d
* Monaco - 2.5dish
* Frozen Synapse - 2.5dish
* Fez - 2.5d - 3d world
* Feist - 3d (use's Limbo-est aesthetics)
* Limbo - 3d (styling / thematic visual style)
* Audiotorium - 3d ish
* Journey - 3d (minimalist in some aspect)
* Audiosurf - 3d (minimalist in some aspect)
* CubeMen - is a 3d Mac OS / PC shooter.
* Edge (iPhone game) very minimalist. 3d - 2.5d
* Antichamber Game (minimalist and confusing)

"The best advice I learned at the GDC 2012 Writing Better Games Narrative workshop is that students should focus on - this : "Game Play is king". -- Everything else will follow as long as gameplay is the primary focus."

Edit : * Sorry these are mostly 2d games.
> 4 votes

# Answer
* Flotilla
* Atom Zombie Smasher
* Bit.Trip series
* All old-school roguelikes, like Nethack, Angband, ADOM, and Dwarf Fortress of course.
> 3 votes

# Answer
Games with minimalist graphics and great game play:

* Darwinia and Multiwinia
* Frozen Synapse
* A New Zero (http://www.crypticsea.com/anewzero.html)
* Knytt (http://nifflas.ni2.se/?page=Knytt)
* Avadon, Avernum, Geneforge
> 2 votes

---
Tags: game-design, game-mechanics
---


title: What is this JavaScript gibberish?

text:
# Question
Title: What is this JavaScript gibberish?
I am studying how to make a 2D game with JavaScript by reading open source JavaScript games and I came across this gibberish...

```
aSpriteData = [
    "}\"¹-º\"À+º\"À+º\"À+º\"¿¤À ~C_ +º\"À+º\"À+º\"À*P7²OK%¾+½u_\"À<¡a¡a¡bM@±@ª",    //  0 ground
    "a ' ![± 7°³b£[mt<Nµ7z]~¨OR»[f_7l},tl},+}%XN²Sb[bl£[±%Y_¹ !@ $",        //  1 qbox
    "!A % @,[] ±}°@;µn¦&X£ <$ §¤ 8}}@Prc'U#Z'H'@· ¶\"is ¤&08@£(",           //  2 mario
    "  ´!A.@H#q8¸»e-½n®@±oW:&X¢a<&bbX~# }LWP41}k¬#3¨q#1f RQ@@:4@$",         //  3 mario jump
    "   40 q$!hWa-½n¦#_Y}a©,0#aaPw@=cmY<mq©GBagaq&@q#0§0t0¤ $",         //  4 mario run
    "+hP_@",                                    //  5 pipe left
    "¢,6< R¤",                                  //  6 pipe right
    "@ &  ,'+hP?>³®'©}[!»¹.¢_^¥y/pX¸#µ°=a¾½hP?>³®'©}[!»¹.¢_^  Ba a",        //  7 pipe top left
    "@ , !] \"º £] , 8O #7a&+¢ §²!cº 9] P &O ,4    e",              //  8 pipe top right
    " £ #! ,! P!!vawd/XO¤8¼'¤P½»¹²'9¨  \"P²Pa²(!¢5!N*(4´b!Gk(a",            //  9 goomba
    "   Xu X5 =ou!¯¬a[Z¼q.°u#|xv ¸··@=~^H'WOJ!¯¬a=Nu ²J <J   a",          // 10 coin  // yui
    "@ & !MX ~L \"y %P *¢ 5a K  w !L \"y %P *a%¬¢ 4  a",               // 11 ebox // yui
    "¢ ,\"²+aN!@ &7 }\"²+aN!XH # }\"²+aN!X%  8}\"²+aN!X%£@ (",          // 12 bricks
    "} %¿¢!N° I¨²*<P%.8\"h,!Cg r¥ H³a4X¢*<P%.H#I¬ :a!u !q",         // 13 block
    makeSpace(20) + "4a }@ }0 N( w$ }\" N! +aa",                    // 14 bush left
    " r \"²y!L%aN zPN NyN#²L}[/cy¾ N" + makeSpace(18) + "@",            // 15 bush mid
    makeSpace(18) + "++ !R·a!x6 &+6 87L ¢6 P+ 8+ (",                // 16 bush right
    " %©¦ +pq 7> \"³  s" + makeSpace(25) + "@",                 // 17 cloud bottom left
    "a/a_#².Q¥'¥b}8.£¨7!X\"K+5cqs%(" + makeSpace(18) + "0",             // 18 cloud bottom mid
    "bP ¢L P+ 8%a,*a%§@ J" + makeSpace(22) + "(",                   // 19 cloud bottom right
    "",         // 20 mushroom
    "", // koopa 16x24
    "",             // 22 star
    "",                         // 23 flagpole
    "",         // 24 flag
    "",                 // 25 flagpole top
    "  6  ~  }a }@ }0 }( }$ }\" }! } a} @} 0} (} $} \"² $",             // 26 hill slope
    "a } \"m %8 *P!MF 5la\"y %P" + makeSpace(18) + "(",             // 27 hill mid
    makeSpace(30) + "%\" t!DK \"q",                         // 28 hill top
    "",         // 29 castle bricks
    "",                         // 30 castle doorway bottom
    "",                 // 31 castle doorway top
    "",         // 32 castle top
    "",         // 33 castle top 2
    "",             // 34 castle window right
    "",             // 35 castle window left
    "",         // 36 castle flag
    makeSpace(19) + "8@# (9F*RSf.8  A¢$!¢040HD",                    // 37 goomba flat
    "     *(!¬#q³¡[_´Yp~¡=<¥g=&'PaS²¿ Sbq*<I#*£Ld%Ryd%¼½e8H8bf#0a",         // 38 mario dead
    "   =  ³ #b 'N¶ Z½Z Z½Z Z½Z Z½Z Z½Z Z½Z =[q ²@ ³  ¶   0",           // 39 coin step 1
    "   ?@ /q /e '¤ #³ !ºa }@ N0 ?( /e '¤ #³  ¿  _a  \"",               // 40 coin step 2
    "   /  >  ]  º !² #¢ %a +  >  ]  º !² #¢ 'a  \"",               // 41 coin step 3
    "   7¢ +² *] %> \"p !Ga t¢ I² 4º *] %> \"p  ¡  Oa  \""              // 42 coin step 4
],

```

What does it do? If you want to look at the source file, here it is. Beware, there is more gibberish inside. I can't seem to make sense of any of it.

# Answer
There are two sets of gibberish: `aSpriteData` and `aFont`.

The former is passed to the `loadSpriteData` function and this is the only place it's used. The latter is used in the `writeChar` function and that's the only place *it's* used. Both are decoded by the `base128ToBitString` function.

So: they're base-128 encoded strings which store font and image data.

Source: CTRL+F plus following the variable and function names.
> 6 votes

---
Tags: javascript, html5, web
---