# Question
Title: Why is my Texture becoming slower when it approaches it's destination?
I have a texture drawn on screen. Whenever I click on the viewport it remembers its destination and starts moving towards it, until it is there. This is the code I am using therefore:

```
//Check if destination was reached
if ((currentDestination - position).Length() <= movementSpeed)
{
     // Stop moving
     position = currentDestination;
     playerState = PlayerState.Idle;
     reachedDestination = true;
}

// If destination is not reached
if(!reachedDestination)
{
    Vector2 direction = (currentDestination - position); // gives the direction needed to travel from position to target
    angle = (float)(Math.Atan2(direction.Y, direction.X) + MathHelper.PiOver2);

    direction.Normalize(); // we need it as a unit vector

    position += direction * movementSpeed;
    // The Y coordinate stays the same in this case
    position.Y = 455;
}

```

It does work, but the closer the texture is to the destination, the slower it gets. Why is that?

# Answer
> 5 votes
I believe this is the line giving you trouble.

```
position.Y = 455;

```

The way you're doing this, the X component of the velocity is getting smaller. `direction` is always changing. Even though the distance is closing on the X axis, it stays the same on the Y-axis. So, when it's normalized, the Y distance is relatively greater, so X will get smaller. Something along the lines of this would work.

```
Vector2 alignedDestination = new Vector2(currentDestination.X, 455); //Added line
Vector2 direction = (alignedDestination - position); // gives the direction needed to travel from position to target

```

---
Tags: xna, textures, movement
---


# Question
Title: HTML5 - Dynamic canvas grid for scrolling a big map
I've been working on different scrolling algorithms for my JS-based game. My main problem is that I need to draw a huge map and also have it scroll smoothly. I've made a few attempts and while they're efficient (code and framerate wise) they still look jumpy and have to redraw constantly (though not each frame, it's still too much redrawing for my taste).

My latest idea is to implement some kind of 3x3 grid around the camera which will scroll with delay. What do I mean "with delay" ? well, if you have played Diablo II before, try to get a Maphack app and enable the Automap Screen Area feature: You see, Diablo II's map is made through a concept of "rooms" and those adjacent to the player in a specific area (usually screen size) are drawn offscreen to allow the scrolling.

I want to implement that in an orthogonal perspective (this is, 2D zelda-like), just like this:

The blue grid is made out of canvases around my camera's position. I know I can position them with the simple x+(floor(camera.x / tile\_size) * tile\_size) formula and with some offsets have them move around the camera like this:

THE PROBLEM arises when the drawn offscreen areas must remain in the same position to allow the scrolling. I've made a second image which illustrates this:

Notice how the colored tiles (or offscreen areas of screen size) remain in the same position UNTIL they get "too far" from the camera (the red dot). HOWEVER, while they have the same position, notice the Tile # (below each blue grid tile) change. I can't do it that way because it would require to redraw, and my goal is to avoid such redraw if the position hasn't changed.

This means however, that, taking in example blue tile 6 (located at 0,1 at the first animation frame) it changes to tile 5 and then to tile 1. While this is true, the idea is to keep it at tile 6, and only re-use the farthest canvases in the closest ones that need to be redrawn.

I'm illustrating my problem this way because my previous question didn't even get a single comment ( https://stackoverflow.com/questions/22185858/infinite-scroll-a-canvas-with-a-tiled-map-without-redrawing/22277681 ) so I had to work and answer my own question... something that doesn't even help either because someone else might have had a better idea, but nobody did, it seems.

That's why I'm asing here in gamedev, maybe here are some more skilled people who can have an idea or a shot at what I'm attempting to do. Also, please, I'm not interested in using other game or JS engines. If I were I wouldn't be asking this here as I know they implement tile scrolling and such, but this is both for my own learning and for creating a custom engine suited for my own game's needs.

Any help then, is really welcome.

Thanks in advance! \- DARKGuy

**EDIT:** Well alright, after struggling for like 2 days straight on this issue I finally managed to do it. I didn't want to do it with this kind of coords, so I wonder is there any way to optimize this code or to avoid it to do those increments and instead use a formula that would absolutely position them?

Here's the code I'm using (cv = canvas, cx = context("2d"), grid = 3x3 array of canvases. Also, I'm using a 32x32 "grid" just to see how it works. The size should be screen size (or region size, in my engine's case)):

```
for(ix = 0; ix < grid.length; ix++)
for(iy = 0; iy < grid.length; iy++) {
    cv = grid[iy][ix];
    if(cam.x - cv.x > 48)
        cv.x += 32 * 3;
    if(cam.x - cv.x < -48)
        cv.x -= 32 * 3;
    if(cam.y - cv.y > 48)
        cv.y += 32 * 3;
    if(cam.y - cv.y <- 48)
        cv.y -= 32 * 3;
    cx.fillStyle = cv.color;
    cx.fillRect(cv.x, cv.y, 32, 32);
}

```

# Answer
> 4 votes
Well fine, after 4 days and 62 views and only ONE comment (thanks @Anko), I managed to do the formula on my own. I don't know if it's as optimized as it should be, but who cares anyways? I can't believe that out of 62 views I only got one user interested in helping...very disappointing.

Anyways, here are the formulas for those interested (`ix/iy` = absolute world coordinates):

X = ( (SCREEN_WIDTH * 3) * (Math.floor( (ix+(SCREEN_WIDTH*(1-j))) / (SCREEN_WIDTH * 3) ) ) + SCREEN_WIDTH * j ) - ix;
Y = ( (SCREEN_HEIGHT * i) + ( (SCREEN_HEIGHT * 3) * Math.floor( ( (iy+(SCREEN_HEIGHT*(1-i))) / (SCREEN_HEIGHT * 3)) )) ) - iy;```
</code></pre>

*Usage:*

```
for(var i = 0; i < 3; i++)
for(var j = 0; j < 3; j++) {
    var cvg = grid[i][j];
    cx.fillStyle = cvg.color;
    var vy = ( (SCREEN_HEIGHT * i) + ( (SCREEN_HEIGHT * 3) * Math.floor( ( (iy+(SCREEN_HEIGHT*(1-i))) / (SCREEN_HEIGHT * 3)) )) ) - iy;
    var vx = ( (SCREEN_WIDTH * 3) * (Math.floor( (ix+(SCREEN_WIDTH*(1-j))) / (SCREEN_WIDTH * 3) ) ) + SCREEN_WIDTH * j ) - ix;
    cx.fillRect(vx, vy, SCREEN_WIDTH, SCREEN_HEIGHT);
}

```

Working JSFiddle.

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


# Question
Title: Why do my update and draw loops throw a concurrent access exception?
I've taken up the challenge of creating a basic 2D side-scrolling monster truck game for my little brother. It seems easy enough in theory, but jumping into Java out of XNA feels strange.

My game class has a private class `GameLoop` extending `Runnable`. In the overridden `run()` method, a `while`-loop handles time and such. There's a `targetFPS` for drawing as well. The loop looks like this:

```
public void run()
{
    long fpsTime = 0;

    gameStart = System.currentTimeMillis();
    lastTime = System.currentTimeMillis();

    while(game.isGameRunning())
    {
        currentTime = System.currentTimeMillis();

        long ellapsedTime = currentTime - lastTime;

        if(mouseState.leftIsDown)
        {
            que.add(new Dot(mouseState.getPosition()));
        }

        entities.addAll(que);

        game.updateGame(ellapsedTime);

        fpsTime += ellapsedTime;
        if(fpsTime >= (1000 / targetedFPS))
        {
            game.drawGame(ellapsedTime);
        }

        lastTime = currentTime;
    }

```

I'm running into a problem when adding entities after a click. I made a class with a private class extending `MouseListener` and `MouseMotionListener`, then on changes I have it set a few booleans to tell me if the mouse is pressed or not which seems to work great. However, when I add the entity, I occasionally get a CME (Concurrent Modification Exception). All the entities are stored in a `LinkedList<Entity>`.

I also tried adding a queued `LinkedList`, where I add the contents of the queue to the normal list later in the update loop.

I think this would work fine if it was just the update method in the game loop, but it's the `repaint()` method (called from `game.drawGame()`) that throws the CME.

The only other thing is that I'm currently drawing directly from the overridden `paintComponent()` method in a custom class extending `JPanel`.

Is a better way to go about this? How do I fix the CME?

# Answer
If you're modifying a `LinkedList` on one thread (game loop thread), and iterating through it on another thread (the EDT, which is drawing your game), then you'll get the `ConcurrentModificationException`.

If you know you'll add new elements rarely, you can try to use a `CopyOnWriteArrayList` which is immune to `ConcurrentModificationException`s, but comes with some disadvantages. Also try using the `addAll` method once at the end of the game loop against a collection of new entities to add to the list.
> 1 votes

# Answer
I don't quite understand why you would face a `ConcurrentModificationException` being thrown unless you're doing bad iterator logic or adding/removing from a collection in one thread while you are iterating the collection in another.

It isn't an uncommon practice to have a *pending* list where entities that are being added and/or removed from the scene are referenced and at a stage in the game loop where concurrency isn't an issue, the master entity list gets updated by adding the new entities and those being removed are deleted.

I generally handle updating the entity list once I receive a FrameEnd event. At this point in my game engine, all data has been rendered, buffers swapped and I'm about to start a new frame.
> 0 votes

---
Tags: java, game-loop, modding, entity, exceptions
---


# Question
Title: How to rotate a 3D character on top of a plane with an isometric picture on it
How to calculate the angles of the 3d charater so that it fits into the isometric environment projektet on a 2d plane?
Also, how do you calculate the rotation of my character?
What I want to achieve: Describing the scenario:

# Answer
First off, you probably want to switch your camera to orthographic, so that you don't get perspective distortion in the image. Then I wouldn't put the image on the ground like that, but rather a plane perpendicular to and linked to the camera. Then rather than rotating the player around, I'd be orienting the camera so that the player looks correct.

The exact position and rotation of the camera is specific to your isometric image, but it looks something like 45 degrees to the right and 45 degrees down.
> 1 votes

# Answer
Changing your camera, like the other fellows said, is probably the best, but if you still need the Camera to have *perspective* projection, you can use `LookAt()`, like this:

```
3dGameObject.transform.LookAt(camera.transform);

```

Basically it makes your game object to rotate in order to **look** at something. Take a look at the documentation for more information on which side of the object (forward) will be looking at the camera and how to specify your "up" coordinate.
> 1 votes

# Answer
You can tell Unity3D to use isometric rendering in the camera settings.

Secondly, you dont use isometrical graphics on a plane, you just build the world in 2D/3D and let the camera make it isometric.

I know this isnt a direct answer about rotation, but if you use my approach, your problem is solved. :-)

I quickly did a Google search on the topic and found this tutorial on YouTube: http://www.youtube.com/watch?v=YqIMbWKeXCA

I also got some articles/tutorials on it, I think this one could be of usage for you too: http://indiehoodgames.wordpress.com/2013/07/21/tip-designing-a-isometric-game-in-unity3d/

Remember, most of the time, someone else has had the exact same problem as you, so Google first. :-)
> 0 votes

---
Tags: unity, isometric, angles
---


title: Particle effect in sprite

text:
# Question
Title: Particle effect in sprite
I want to create a particle effect when my player sprite collide with my star sprite. How can I add a particleSystem in the sprite and not in a image? Also, I wish if it could wait for the animation for some miliseconds, and then remove the star sprite.

This is my code:

```
- (BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair starCollision:
    (CCNode *)star playerCollision:(CCNode *)_player {
    NSLog(@"----------Colisao---------");

    //update score
    score += 1;
    [scorelabel setString: [NSString stringWithFormat:@"score: %d",score]];
    NSLog(@"score %d", score);

    CCParticleSystem *particleSystem = [[CCParticleSpiral alloc] initWithTotalParticles:1000];

    [self addChild:particleSystem];
    //[particleSystem release];
    //[particleSystem setTexture:[[CCTextureCache  sharedTextureCache] addImage:@"star.png"];

    //remove stars
    [star removeFromParent];
    return YES;
}

```

# Answer
I am not seeing where you are positioning the particle system, only that you are adding it to "self". I assume you want the particle system to be more or less at the same position as the star sprite.

Assuming "self" is a layer, you need to position the particle system using the position of the star sprite, and offset the position where needed.

```
particleSystem.position = star.position;

```

Or you could just add the particle system as a child of the star sprite, and offset the position where needed.

```
[star addChild:particleSystem];

```

With regard to waiting some period of time before removing the star sprite, you could use actions to do this. The first action would be a delay, and the second action would then call a method to remove the star:

```
id delayAction = [CCDelayTime actionWithDuration:0.1];
CCAction * removeStar = [CCCallFuncN actionWithTarget:self selector:@selector(removeStar)];
[star runAction:[CCSequence actions: delayAction, removeStar, nil]];

- (void) removeStar {
    [star removeFromParent];
}

```

Your question was not very clear, so this was the best I could do with the information provided. Also, it does not appear that you are properly preparing the particle system. But, since you did not specifically ask about that I am assuming your code just lists the basic information about this.

I hope this helps.
> 1 votes

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


title: Game Update in Libgdx

text:
# Question
Title: Game Update in Libgdx
In libgdx, the game loop is the render() method. But why is that, and is there a way where I can make an update() method that is called 60 times a second? As in the update() method, I would add the game logic, and leave the rendering to the render method. Basically, separate methods, and the update() method called 60 times per second using Libgdx with java.

# Answer
> 7 votes
There is no specific game loop in libGDX because it is event-driven. And still, you can see the render method as the main loop.

You've got it right - usually, this is where you update the game logic before you do the rendering.

What you can do is to create a class responsible for the logic and a class responsible for the rendering. Then in your render method you write

```
@Override
public void render(float deltaTime) {
    if(!paused)
        LogicClass.update(deltaTime);
    Gdx.gl.glClearColor(0, 0, 0, 0);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    RenderClass.render(deltaTime);
}

```

You can read more about the life cycle in libGDX in its wiki on github: https://github.com/libgdx/libgdx/wiki/The-life-cycle.

---
Tags: java, libgdx, game-loop
---


# Question
Title: Converting Projected Vertex Positions to Normalized Device Coordinates
I'm using directx 9 and vertex shaders to rasterize triangles...I have vertex shader input structs like this:

```
struct VS_INPUT_Quad
{
   float4 Position : POSITION;
   float2 UV : TEXCOORD0;
};

```

and pixel shader input structs like this:

```
struct PS_INPUT_Quad
{
   float4 Position : POSITION;
   float4 Pos2 : TEXCOORD0;
   float2 UV : TEXCOORD1;
};

```

Here is vertex shader:

```
    PS_INPUT_Quad SkyboxVisibilityPass_Vertex_Shader( VS_INPUT_Quad Input )
    {
        PS_INPUT_Quad Output = ( PS_INPUT_Quad )0;

// projected vertex position
        Output.Position = mul( Input.Position, mWVP );

// normalized device coordinates of the vertex
        Output.Pos2 = Output.Position / Output.Position.w;
        Output.Pos2.xy *= float2( 0.5, -0.5 );
        Output.Pos2.xy += float2( 0.5, 0.5 );

// prop uv coordinates
        Output.UV = Input.UV;

        return( Output );
    }

```

Here is pixel shader( simply returns a color from a texture ):

```
    float4 SkyboxVisibilityPass_Pixel_Shader( PS_INPUT_Quad Input ) : COLOR0
    {
        return tex2D( g_SamplerMultiplier, Input.Pos2.xy );
    }

```

I'm finding that the Pos2 value sent to the pixel shader is incorrect. Am I incorrectly converting projected vertex position coordinates to normalized device coordinates? PIX says that values are well above 1 when dubugging the pixel shader, however, the output looks correct when looking at the 'mesh' tab while hiliting the draw call...

Here is debug output for a single pixel whose position lies within the clip space:

```
   //
// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
//
// Parameters:
//
//   sampler2D g_SamplerMultiplier;
//
//
// Registers:
//
//   Name                Reg   Size
//   ------------------- ----- ----
//   g_SamplerMultiplier s0       1
//

    ps_2_0
    dcl t0.xy  // Input<4,5>
    dcl_2d s0
    texld r0, t0, s0  // ::SkyboxVisibilityPass_Pixel_Shader<0,1,2,3>
    mov oC0, r0  // ::SkyboxVisibilityPass_Pixel_Shader<0,1,2,3>

// approximately 2 instruction slots used (1 texture, 1 arithmetic)

Registers:
    oC0 (0.435, 0.435, 0.435, 1.000)    float4
r0  (0.435, 0.435, 0.435, 1.000)    float4
s0      float4
t0  (11.871, 8.631, 0.000, 0.000)   float4

```

As you can see above, t0 is the Pos2 coordinates that i use to sample the texture...they are well above 1 ... the vertex they belong to is visible so this pixel should have valid normalized device coordinates. Are the coordinates being altered after leaving the vertex shader and arriving at the pixel shader?

# Answer
You should do `Output.Pos2 = Output.Position` in the vertex shader, then in the pixel shader:

```
float2 screenPos;
        screenPos.x = Input.pos2D.x/Input.pos2D.w/2.0f + 0.5f;
        screenPos.y = -Input.pos2D.y/Input.pos2D.w/2.0f + 0.5f;

```

To get correct screen space coordinates you have to do your w divide in the pixel shader. After that your return should function correctly:

```
return tex2D( g_SamplerMultiplier, screenPos );

```

I hope I could help you.
> 2 votes

---
Tags: c++, hlsl, directx9
---


# Question
Title: How do I merge quads to simplify a heightmap?
I'm trying to improve my frame rates.

My map has an area of 200 * 200 vertices, where each vertex has a height. 200 * 200 = 40000 vertices per frame.

I'd like to create a method to simplify the whole heightmap (i.e. decrease vertex count). Every 4 vertices form a quad, so when there are 2 or more adjacent quads with the same height on each vertex, they could be merged.

How do I detect and merge vertices like that?

My height map is a list of `float`s representing the height of each vertex. The list is indexed by an `x` and `y` coordinate.

```
package rgc.area;

import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;

public class Terrain {

    private HeightMap map;

    public Terrain(HeightMap map) {

        this.map = map;
    }

    public void render() {

        float spaceBetwVert = 1f; // Space between each vertex

        GL11.glColor3f(0.1f, 1.0f, 0.2f);
        GL11.glBegin(GL11.GL_QUADS);
            for(int i = 0; i < map.getHeight() - 1; i++) {

                for(int ii = 0; ii < map.getWidth(); ii++) {

                    GL11.glColor3f(0.1f, 1.0f - ii * 0.1f, 0.2f);

                    float vz = i * spaceBetwVert;
                    float vx = ii * spaceBetwVert;
                    float nextVz = (i + 1) * spaceBetwVert;
                    float nextVx = (ii + 1) * spaceBetwVert;

                    GL11.glVertex3f(vx, map.getHeight(vx, vz), vz - 80);
                    GL11.glVertex3f(nextVx, map.getHeight(nextVx, vz), vz - 80);
                    GL11.glVertex3f(nextVx, map.getHeight(nextVx, nextVz), nextVz - 80);
                    GL11.glVertex3f(vx, map.getHeight(vx, nextVz), nextVz - 80);

                }
            }
        GL11.glEnd();
    }
}

```

# Answer
> 2 votes
I suggest you change the way you render your vertices instead of trying to merge them.

You are using immediate rendering. While good for debugging and proof of concept, it is "deprecated", and not a preferrable way to render when it comes to performance. You have several alternatives, but the most versatile and robust way I would recommend is using Vertex Buffer Objects (VBO's).

You push the vertices to the GPU once (or once they change), instead of every vertex on its own, every time.

Compared to using immediate mode, VBO's can be hard to grasp at first glance, but they're actually not that hard to use. I recommend you start with something really easy, just to confirm that you get it working. LWJGL has some nice tutorials on using VBO's, and instead of writing them down here, I will link to their site so that this answer points to updated tutorials.

http://lwjgl.org/wiki/index.php?title=Using\_Vertex\_Buffer\_Objects\_(VBO)

http://www.java-gaming.org/index.php?topic=24272.0

I am pretty sure this will give you the performance boost you're after.

# Answer
> -2 votes
Use float\[\] or float\[\]\[\] instead of List\[Float\] for the map. if you use List\[Float\] every time you add or get a float value to/from the map Java creates A Float instance form the primitive float value or convert the Float instance to a primitive float value (auto-boxing, -unboxing) this needs more memory and time.

---
Tags: java, lwjgl, optimization, heightmap
---


# Question
Title: Generate Angle for Projectile to Follow So It's Ends Facing Downward
I am building a game within a game engine. The game is a 2D platform, where the player can move left, right, and jump/fall down. Part of the game is the presence of physical projectiles falling from the 'sky'. When these objects are created (in the sky), impulse is applied to them toward the present location of the player \[Pic 1\]. Please note the impulse is applied one time using the location of the player at object location, it is not constantly being applied to the location of the moving player. The projectile should move **toward** that location of the player, not necessarily **to** the location - and it does - but as it reaches its destination the object starts to curl upward \[Pic 2\].

I have tried several formulas for setting the angle on each tick (every frame), namely

```
Set Angle Toward: PlayerWasAtX, LayoutHeight
Set Angle Toward: Self.X, LayoutHeight
Set Angle Toward: If (Self.X > Self.PlayerWasAtX)
                  Then (Self.X - PlayerWasAtX) / 2
                  Else (PlayerWasAtX - Self.X) / 2
                  , LayoutHeight

```

Where `PlayerWasAtX` is the stored location of the player upon projectile creation, `LayoutHeight` is the total height of the canvas, and `Self.X` is the X-coordinate of the projetile.

In those examples, example 1 would curl, example 2 would keep the object straight down at all times even when falling at a curve, and iirc example 2 just acted wacky.. or it acted the same as example 1.

Any help would be appreciated. Here are my reference pictures:

# Answer
> 1 votes
You need to set the angle to be the derivative of motion or in lament terms, the angle needs to be between the previous position and the current position.

Specifically, store the previous position `prev.x`, `prev.y` somewhere. The on the next frame where you already have calcualted the new position `curr.x`, `curr.y`, you calculate the angle between `prev` and `curr` and use that for the projectile.

I don't understand the mechanism you are using but it appears to rely on `X` alone which is bad. The angle should be determined by `x` & `y` and relying on the current `x` & `y` and the previous ones.

---
Tags: 2d, physics, angles
---


# Question
Title: How do I apply a texture over a material in OpenGL ES?
How can I apply a texture over a material?

I've set up an object with the following material:

```
GLKBaseEffect *effect;
effect.colorMaterialEnabled = false;
effect.material.ambientColor = GLKVector4Make(251.0/255.0, 95.0/255.0, 96.0/255.0, 1.0);
effect.material.diffuseColor = GLKVector4Make(251.0/255.0, 95.0/255.0, 96.0/255.0, 1.0);

```

and it is correctly rendered with a pink color.

However, when I apply a texture with:

```
GLKTextureInfo * info = [GLKTextureLoader textureWithCGImage:...];
effect.texture2d0.name = info.name;
effect.texture2d0.enabled = true;

```

the material seems to disappear and I just see the texture; the object is transparent where the texture is not visible, instead of being pink.

---

Here's an example:

The texture is created with the following code:

```
- (UIImage*)generateTexturefromText:(NSString*)text {
    NSError *error;

    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    myLabel.text = text;
    myLabel.font = [UIFont fontWithName:"Helvetica" size:50];
    myLabel.textAlignment = NSTextAlignmentLeft;
    myLabel.textColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1];
    myLabel.backgroundColor = [UIColor clearColor];
    myLabel.numberOfLines = -1;
    myLabel.lineBreakMode = NSLineBreakByCharWrapping;

    UIGraphicsBeginImageContextWithOptions(myLabel.bounds.size, NO, 1.0);
    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, 0);
    CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, 1.0);
    [myLabel.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *layerImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    if (error) {
        NSLog(" Error loading texture from image: %",error);
        return nil;
    }

    return layerImage;
}

```

Why is no color visible where the texture is transparent?

# Answer
Resolved!

```
effect.texture2d0.envMode = GLKTextureEnvModeDecal;

```

It is related to the Texture Environment Parameters, i.e. how OpenGL combines the diffuse color of the material with the texture value.

As described here: khronos.org/opengles/sdk/1.1/docs/man/glTexEnv.xml. If I'm right that GLKit instruction should correspond to:

```
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

```
> 3 votes

---
Tags: textures, opengl-es, materials
---


# Question
Title: How were cartridge-based games programmed?
I'm thinking of like the SNES, N64, Atari... even the DS today, I suppose.

SNES games did not usually take up more than 4 MB of space, and N64 games were usually 32 to 64 MB worth of data.

These days, you can barely compile a "hello world!" program without the resulting compilation generating 1.21 gigabytes!! of data. (Joking aside, files today do take up tons and tons of space compared to some of the technology back then.)

So... how did they do it?

* What did they program these games in? ASM? *The entire thing in ASM?!*
* How were graphics created? What technology did they have to create sprite sheets and, in some cases (like the N64), 3D models?
* How did they fit so many levels, characters, quests and items on these cartridges? I mean, Super Mario World on the SNES clocks in around 1 MB, and it has 96 exits! Ocarina of Time, Banjo-Kazooie, DK64 and a few other games take up less than 64 MB and had huge worlds, tons of content and 3D models!

Sorry if my questions seem a little out-there, I'm just amazed that a lot of great titles out there managed to fit in such a small storage space.

It's fascinating to me because even tiniest and most trivial of files and games manage to take up at least a few MB, so imagining that huge levels like those in GoldenEye 007 managed to take almost no data at all is mind-blowing.

# Answer
> 28 votes
It's the art and audio resources that take up space, choice of programming language was more about getting the most of out of the hardware.

Using N64 as an example, most of the 3rd party games were 8, 12, or 16Mb. The 32 & 64Mb games were mostly from Nintendo as it was so expensive to ship on carts that big for everyone else. That sounds tiny, but then so were the art assets and the final visual output. You have to remember that most N64 games rendered at 320x240 not the 1280x760 or more of today. With such a small output resolution, textures and sprites were much smaller than they are today.

Because of the tiny texture cache on the N64, most textures were 32x64 pixels with a 4/8bit palette (aka 16/256 colors). Extra color detail was often done by mixing textures and vertex colors. The Banjo games are a good example of this.

Today a single rock in an Unreal engine game will have multiple 512x512x24bpp or even 32bpp. Plus instead of just a single diffuse texture, you've now got normal maps, specular masks, reflection masks, reflection cubemaps and more. So an object that used to have 4Kb of textures is now covered in several MB of data.

Old games also have a massive amount of reuse of art. The bushes in Super Mario Bros. are the same sprites as the clouds, the hills are the same as the mushrooms. Different characters are just color shifted versions of the same art resources. All of this got more usage out of each texture or sprite that was on the cart.

Audio is another big difference for modern games. Nearly everything in the old days was done with sequenced tracks. Now both music tracks, voice and sound effects are stored in various compressed audio formats. While certainly smaller than uncompressed data, they are still significantly bigger than their sequenced equivalents.

# Answer
> 14 votes
As for the NES (and SNES too mostly), here's a basic overview. I did not write any NES games but did write an NES emulator (Graybox) and did a fair amount of rev-engineering of old carts.

As for programming language: yes, it was all assembly. Programming the NES meant working directly with hardware interrupts, DMA ports, bank switching etc. Luckily, programming the 6502 (or rather, the 2A03) is quite easy\[1\]:

* there are few registers: A, X and Y mainly, the latter two being usable only for indexing and iterating
* the instruction set is small and mostly straightforward
* not a lot of memory: main RAM is 2KB, with an optional battery backed 8KB extension. Of that 2KB, 256 bytes are reserved for the stack and page 0 (the first 256 bytes) was where you'd want to store your most used pointers and values because of some special addressing modes

These 3 things together make for an environment that is easy enough to memorise while working with it. Yes, you manage all memory yourself but that meant essentially that you create a full map of where everything goes up ahead and that map isn't very big because you only have to worry about 2K, so you could plot that out on a piece of graph paper. You had to plan things out a bit more and statically assign variables and constants to RAM and ROM (on cartridge) locations.

It gets a bit tricker once your cartridge data goes beyond the addressable limits of the CPU. That's 64KB, of which the lower 32KB is set in stone and mapped to all kinds of hardware ports and RAM. This is where bank-switching comes into play, which means mapping a section of the ROM into (part of) the higher 32KB address space.

This can be used however the programmer wants, but an example use might be having a game with 3 levels, with all the level data, meta data and code for each level crammed into separate 8KB memory areas on the cartridge. The level might have callbacks for e.g. initialisation, per frame update, etc. "Loading" the level would mean mapping that 8KB chunk of memory at e.g. 0xC000. You could then specify that the init routine is always at 0xC000, the frame update routine is at 0xC200 and the level data starts at 0xC800. The game's main code housed in another memory chunk then controls level changes simply by swapping in the right chunk and jumping to absolute addresses 0xC000 and 0xC200 at the appropriate times.

W.r.t. graphical data: the NES's tiles data are 2-bit 8x8 pixel maps. For the background they are combined with a 1/4 resolution 2-bit layer. These 4-bit values were then indexed into a 16-entry palette, with I believe 53 effective unique colours available. Sprites also used the 2-bit pixel data and each sprite specified its own 2-bit group index again forming a 4-bit pal index. The BG image on screen is a 32x30 array of tile index numbers.

Essentially, by having a ton of repetition and indexes into indexes you can keep data very small. Level data was often stored as vertical bars of tile indexes and because those vertical bars were re-used as well, those were indexed as well and only stored once on the cartridge. Simple data compression techniques work similarly. This allowed Mario 1 to be 32KB of data (with room to spare) and 8KB of bitmap data.

As for dev environments, I've seen some photos where people worked on some certifiably ancient computers hooked up to EEPROM burners for work. Tool-assisted debugging was not really a possibility until after the SNES age\[2\]. This is the main reason so many old games have "obvious" bugs in them and why things like Gameshark could do what they do; player health would always be at mem-location X, so you can force it to be 100 at all times.

If you find these things interesting I encourage you to look at e.g. http://wiki.nesdev.com/w/index.php/Nesdev\_Wiki There are quite a few programming courses for NES to be found online as well.

I hope this simplified overview gave some insight into 80s-era game development.

\[1\] Relatively speaking. Also I'm biased as I wrote Graybox itself in about 85% PowerPC assembly. \[2\] See the making of FF6 article: http://www.edge-online.com/features/the-making-of-final-fantasy-vi/

# Answer
> 3 votes
There are a lot of sub-topics in almost all of the questions you are asking. Optimization is a huge field all to itself and there are a lot of things to explore.

If you are interested in this sort of optimization, one of the things you might explore is the demoscene. The demoscene, and some of its related art cultures, has long retained a sense of wonder about trying to create intricate art for computers that takes up as little space as possible. Many of them will have information on how they did some or all of their "tricks".

Often there is an artful mix of common sense, although there are "tricks" and "hacks" specific to a game or genre. Often there's a bit of "luck" involved, and a team knowing the limits they are working for (perhaps continually butting heads with those limits throughout the process), knowing their available trade-offs, and be willing to make some of the necessary trade-offs and sacrifices to meet their limits.

Here are some of the things that I can think of that can help a team get a game to smaller sizes:

* Reuse What You Can: reusing the same sprites, and the variations that you can easily make from a single sprite image (such as reflections, rotations, palette shifts) will save you space. The same goes for code, music, and nearly everything else in a game.
* Compress What You Can: there are a number of compression schemes out there, and knowing which ones to use can be a huge space savings. Even sometimes simple compression schemes like run-length encoding can make a surprising difference. Not only that, but there are compression schemes (and alternative formats that aren't exactly compression) for individual file types, often with quality trade-offs. For instance, wave/CD audio files can be compressed, with some marginal loss of information, into MP3 files. Also, file formats like MIDI and sampler-based MOD are alternative formats that take up a lot less space, but encode music entirely differently and require different skills to make them sound good.
* Lose What You Don't Need: can you do it cheaper? For instance, can you still get the "personality" of a character across in fewer pixels (or polygons)? Does the placement of tiles need to be exactly defined by a designer or can they be randomly generated in your program code?
* Code Is Often Cheaper: although you made a joke about how much space a code compile typically takes now ideas (and there are reasons for why this 'platform' has increased over the years, and ways to shrink it when you absolutely need to), but generally if you can do something algorithmically/procedurally/in-code easily, that approach will also be easier to tweak and to reuse for other similar but different looking/feeling assets. Fractals are a particularly easy to see example: you could have an image of an intricate fractal that takes up a lot of space with comparison to the mathematical formula that generates it. The mathematical formula, additionally, may have parameters that can generate similar, but sometimes surprisingly different looking images.

Anyway, for such a big, loaded set of questions, hopefully some of the topics above will be good starting points for you to learn more.

# Answer
> 0 votes
One thing is I am not sure if it still stands in the post N64 era but the SNES and N64 often reused textures on other 3D objects which often save considerable space and pre rendered art which the backgrounds are often fake. Another trick was to create a border background fog would be used.

San Francisco Rush N64 always had some fog though settings could change the density where the San Francisco Rush arcade didn't have any and you could see the Golden Gate Bridge on Track 1 compared to the N64 version.

Also games often reuse music like Zelda Ocarina of Time reuses music a lot which I find annoying as there could've been done a better job like how Banjo Kazooie/DK64 often had themes within themes!

Zelda Ocarina of time could've had the Hyrule Overworld and then an underwater version of the theme if you go underwater or make the instruments in the Shop Theme reflect the outside area where flutes and fiddles would be used for the Kokiri Forest shop and horns and trumpets for the Hyrule Castle Town shop and drums in the Goron village.etc

In PC's 3D modules are compiled into libraries to quickly access them using a program to unpack it but I am not sure if that is the case with Nintendo which is ROM based. PC's is RAM like going into a messy room in which things don't always stay where they are suppose to and information can be overwritten to the point the computer won't even start!

Game Consoles are ROM where everything is stored in an allotted space so every time you turn the game on it will look for the files in that allotted space with a guarantee it will remain there.

---
Tags: game-industry
---


# Question
Title: Player & Level class structure in 2D python console game?
I'm trying to create a 2D console game, where I have a player who can freely move around in a level (~map, but `map` is a reserved keyword) and interfere with other objects. `Level`s construct out of multiple `Block`s, such as player(s), rocks, etc.

Here's the `Block` class:

```
class Block(object):
    def __init__(self, x=0, y=0, char=' ', solid=False):
        self.x = x
        self.y = y
        self.char = char
        self.solid = solid

```

As you see, each block has a position (`x, y`) and a character to represent the block when it's printed. Each block also has a `solid` attribute, defining whether it can overlap with other `solid`s or not. (Two solid blocks cannot overlap)

I've now created few subclasses from `Block` (`Rock` might be useless for now)

```
class Rock(Block):
    def __init__(self, x=0, y=0):
        super(Rock, self).__init__(x, y, 'x', True)

class Player(Block):
    def __init__(self, x=0, y=0):
        super(Player, self).__init__(x, y, 'i', True)

    def move_left(self, x=1):
        ... # How do I make sure Player wont overlap with rocks?
        self.x -= x

```

And here's the Level class:

```
class Level(object):
    def __init__(self, name='', blocks=None):
        self.name = name
        self.blocks = blocks or []

```

Only way I can think of is to store a `Player` instance into `Level`'s attributes (`self.player=Player()`, or so) and then give `Level` a method:

```
def player_move_left(self):
    for block in self.blocks:
        if block.x == self.player.x - 1 and block.solid:
            return False

```

But this doesn't really make any sense, why have a `Player` class if it can't even be moved without `Level`? Imo. player should be moved by a method inside `Player`.

Am I wrong at something here, if not, how could I implement such behavior?

# Answer
You have different options:

**Option 1: Not making a Player class**

You keep a level attribute: `self.player = Block()`. Then you don't have to worry for having an extra class. But in the future you might want to add extra methods/attributes to player, so perhaps it isn't the best option.

**Option 2: Player receives blocks**

```
def player_move_left(self):
    self.player.move_left(self.blocks)

# Then implement the movement in the player class

```

**Option 3: Player receives the whole level**

Player doesn't need to be an attribute of your level if you keep player as a global, ie:

```
player.move_left(level)

class Player(Block):
    ...

    def move_left(self, level):
        for block in level.blocks:
            if block.x == self.player.x - 1 and block.solid:
                return False

```

Even better, level could have a `can_move` method:

```
    def move_left(self, level):
        if level.can_move(self.player.x - 1):
            self.player.x -= 1
            return true
        else:
            return false

```
> 1 votes

---
Tags: python, data-structure, text-based
---


# Question
Title: How can I calculate force and acceleration?
I have problem of calculating the movement of the object.

At the moment, I have a vectors calculated from the center of the screen minus the position of the object.

```
direction vector = centerScreen - positionObject

```

To calculate the new position of the object

```
position(new) = position(t) + directionVector * delta

```

The delta is the time frame rate.

Does anyone know how can I modify the above formula to calculate forces and acceleration? I want to have an object pulling other objects towards it.

# Answer
> 2 votes
While the equations

> v(n+1) = v(n) + a
> d(n+1) = d(n) + (v(n+1) + v(n)) / 2

with:

* d(n) is position at time n;
* v(n) is velocity at time n; and
* a is acceleration in distance units per frame per frame

are arithmetically (and physically) correct, they are computationally problematic.

The faster your frame rate becomes the larger the computational error arising from floating point approximation becomes as a fraction of your values for velocity, acceleration and time. Then the further out you extrapolate these approximations from the last change in acceleration, the greater the accumulated error in position and velocity becomes.

The problems arise in attempting to calculate intersection of targeting vectors, or predict future positions.

A better computation is to directly calculate position and velocity from the initial values at the last acceleration change and the elapsed time as:

> v(n) = v(0) + a * n
> d(n) = d(0) + (a * n * n) / 2

where v(0) and d(0) are respectively the position and velocity at the time of the last acceleration change, and n is the number of frame time-units since the last acceleration change.

To compute the gravitational force between two objects one uses Newton's gravitational law:

> F = m1 * m2 * G / (r * r)

and the gravitational acceleration experienced by each mass due to the other will be

> g = M * G / (r * r)

where G is the Gravitational Constant

Note that the gravitational acceleration experienced by each mass is only proportional to the mass of the other object, not it's own.

Generalizing the homily above on computational accuracy and precision, with non-constant but calculable acceleration such as in this case, it would be better to use the appropriate Calculus formulae to calculate position and velocity directly at each frame than to calculate each indirectly from the immediately previous values.

# Answer
> 3 votes
Every frame:

`acceleration` \<-- from input

```
velocity = velocity + acceleration * t
position = position + velocity * t

```

with `t`= time passed since last frame

**UPDATE:**

Reading again the question I thought you would need also the direction. I didn't specified because I assumed that `acceleration`, `velocity` and `position` are vectors.
By the way **if you have just the magnitude** you need to take your direction vector, normalize it and multiply it times the magnitude.

# Answer
> 1 votes
You just have to add acceleration to your speed.

For every "frame" you have to do

v = u+at

where v is the new speed, u is the old one, a is the acceleration and t is the time

http://en.wikipedia.org/wiki/Linear\_motion#Acceleration

---
Tags: physics, movement, vector, direction
---


title: Connecting Circular Rooms

text:
# Question
Title: Connecting Circular Rooms
My roguelike generates a number of circular rooms. I quite like the current results, which look something like this:

It's generated by carving out random circles in a filled space.

I have one main problem with it: several circles are completely unconnected. I cna't quite figure out what algorithm to use to connect them.

I tried "for each circle, find the nearest circle, and tunnel to its center (horizontally then vertically)," but I get something horrible instead (same map as above):

What seems to be the right fit is something like "for each self-enclosed space, find the nearest empty space and tunnel to it." That seems complexity-hard though (for each circular enclosed space, compute the distance to every other space) and will probably be slow (running on Ruby too)

Is there a simple solution to this problem?

# Answer
Unfortunately, both of Arthur's solutions did not prove usable for me; it came down to a problem which is solvable, but didn't run fast enough (took an order of magnitude of seconds to run; I need something almost instantaneous.)

This is perhaps my fault, because I did not implement everything exactly as he suggested, but instead went for simpler code (over faster code).

That said, I found a simple solution which is fast to run and easy to code. The main steps are:

* Assume the "starting" room is not the biggest, but the room the player spawns in
* For every unconnected room, find the closest connected room (O(n^2))
* Create a tunnel connecting the two rooms

This is not a minimum spanning tree, so there are cases where the order matters -- I iterate rooms in the wrong order, and end up connecting them a longer way instead of a shorter way.

For my game and requirements, this worked. In the future, I may expand it by using a minimum spanning tree instead.

For posterity, here's the same floor generated with my solution.

You can see a snapshot of the core code on GitHub, starting here.
> 1 votes

# Answer
Alright. There is a rather computationally inexpensive solution for this issue. First use Union Find to keep track of rooms that are not connected yet.

Each square will now belong to some set with a unique index.

1. When you create a circular room, merge all squares inside of it to the same set.
2. When you create a room that overlaps with another room, unify the two sets into one.
3. Once you are done, you should have a bunch of spaces, each connected space has it's own unique ID in the union find data structure.
4. Pick the largest open space (you need to keep track of the size of sets in union find).
5. Treat the map as a graph of nodes where each node is connect to it's left, right, up and down by an edge. If an edge leads to a wall, it costs (1), otherwise it costs `epsilon` 0.0001. All other rooms (empty spaces) will be connected to a virtual destination node with a free edge.
6. Use Dijkstra to find the shortest path from the current room space to the destination and clear that path by removing the walls in this path.
7. Now merge the sets (the joined rooms) and continue this process with Dijkstra.
> 6 votes

# Answer
Arthur's answer seems to solve your problem, but here is an easier approach:

1. start from from one of the empty cells.
2. using BFS algorithm, mark all the cells in that area.
3. add all the nodes visited in previous step to start list of new BFS algorithm, and using it explore through the walls until you find some other empty area not already visited
4. clear the path your second BFS took to reach the new area.
5. repeat process from step 2, until all the cells are visited.

note that in each repetition you just have to continue previous BFS. I mean restarting the algorithm from the beginning will only reduce your performance, and it won't generate any better results.
> 1 votes

# Answer
If you want a simpler solution still, since the rooms are simple and circular you could do this instead:

1. Pick one room at random.
2. Add it to the (currently empty) list of `visited` rooms.
3. Iterate over some data-structure that contain all `unvisited` rooms and find the closest `unvisited` room. If the distance between them is smaller than the sum of their radiuses then there is probably no reason to connect them but at any case "draw" a corridor with one non-straight line between their centers(I will describe the algorithm later).
4. Reiterate over all `unvisted` and find the one closest to one of the `visited` ones.
    * `min [(xu-xv)^2 + (yu-yv)^2]`.
5. Connect the two rooms, add the new room to the `visited`, remove from the `unvisited` and repeat until all rooms are all `visited` successfully.

This should work find with a map that has less than a hundred rooms but could be improved in computational efficiency in many ways (that are irrelevant to the question).

To draw a non-straight line use the following pseudo algorithm:

The code was taken from here

```
       /**
        * Draw a line
        *
        * @param x0     first point x coord
        * @param y0     first point y coord
        * @param x1     second point x coord
        * @param y1     second point y coord
        * @param c      color (0xaarrvvbb)
        */
        public function line ( x0:int, y0:int, x1:int, y1:int, color:uint ):void
        {
            var dx:int;
            var dy:int;
            var i:int;
            var xinc:int;
            var yinc:int;
            var cumul:int;
            var x:int;
            var y:int;
            x = x0;
            y = y0;
            dx = x1 - x0;
            dy = y1 - y0;
            xinc = ( dx > 0 ) ? 1 : -1;
            yinc = ( dy > 0 ) ? 1 : -1;
            dx = dx < 0 ? -dx : dx;
            dy = dy < 0 ? -dy : dy;
            setPixel32(x,y,color);

            if ( dx > dy )
            {
                cumul = dx >> 1;
                for ( i = 1 ; i <= dx ; ++i )
                {
                    x += xinc;
                    cumul += dy;
                    if (cumul >= dx)
                    {
                        cumul -= dx;
                        y += yinc;
                    }
                    setPixel32(x,y,color);
                }
            }else
            {
                cumul = dy >> 1;
                for ( i = 1 ; i <= dy ; ++i )
                {
                    y += yinc;
                    cumul += dx;
                    if ( cumul >= dy )
                    {
                        cumul -= dy;
                        x += xinc ;
                    }
                    setPixel32(x,y,color);
                }
            }
        }

```
> 1 votes

---
Tags: procedural, roguelikes
---


# Question
Title: Measuring distances on 2D perspective beat'em'up
I'm making a 2-D beat'em up. The tech demo is here.

As you can see, the game is in perspective, pretty much like all old school brawlers. What I want to do is measure the distance between objects on the level on screen. The game is made on Construct2, so AFAIK the only distances I can work out are absolute and on a straight line, without accounting for perspective. Ideally, I would like a function that says "if this is here and this is here, this is the real distance between these two objects".

I've been reading about perspective matrixes but can't for the life of me understand what they are or how could I use it. I'm not afraid to read though, so if you could point me to something (book, website) that can explain how to do that in layman's terms I'd be most grateful.

Thank you! :D

# Answer
Normally `(x^2 + y^2)^0.5` would give you the distance, however your `y` vector is not straight up and down. It actually represents the true vertical with an additional horizontal component. First, find the angle difference between vertical on the screen and vertical in the game world (probably around 20 degrees.) We'll call this `o`.

`sin o * y = a` (the real vertical offset)

`cos o * a = b` (an additional horizontal offset that needs to be included)

The distance should be: `((x + b)^2 + a^2)^0.5`

See if that works (I might have switched a vector by mistake).

Anyway, the answer is going to require some trigonometry.
> 1 votes

---
Tags: 2d, perspective
---


title: What is a Pool?

text:
# Question
Title: What is a Pool?
According to When and why is a Pool class needed to hold objects?, pools are used when the number of "instances" of an object fluctuates. However, StarWarrior (the Artemis example) uses a pool for the player (of which there is always only one) and no pool for the enemies (which fluctuate and which more exist).

So what is the deal with pools?

Specifically:

* **What are pools?**
* **Why are pools?**
* **Where are pools?**
* What is the difference between `AddComponentFromPool` and `AddComponent` (from
Artemis)?
* What is the difference between extending `IComponent` and `ComponentPoolable` (from Artemis)?

# Answer
Pools are like a recycle been for objects. They are used to avoid unneeded memory management (free and malloc in c, new and delete in c++ ... garbage collection activity in Java and AS3 and so forth).

You basically use a container to store objects (or in c / c++ pointers to objects) that are currently not in use but might be needed soon.

For instance, instead of firing the CTOR (constructor) to create a new enemy instance, only to fire the DTOR (destructor) to deallocate resources once it's dead; you put a bunch of enemies in advance inside a container called a pool. When they are needed, you remove some from the pool and when they are no longer needed (dead or just suspended) you put them back in the pool. Later you can start resetting the appropriate values and reuse these objects.

From what I could tell, the 'AddComponentFromPool' is used when the component inherits from 'ComponentPoolable' which basically means that is relying on pools to help with memory management.
> 0 votes

---
Tags: entity-component, artemis, object-pools
---


# Question
Title: LibGdx and in-game fonts - any proven methods?
I use 3 sizes for fonts in my game: small, medium, and large. I take the base font size and attempt to scale the font based on screen size and density, but this is proving to be pretty hard.

Does anyone have a proven formula for scaling fonts? Right now I'm simply using the pixel width of the screen to put the device into 1x, 2x, and 3x font scale bucket sizes, but I feel like I should be using the screen density in the calculation as well.

# Answer
There are a few methods I used which worked in the past, each has their own pros and cons.

The first was to generate about 10 different sizes of fonts in Heiro as part of a single atlas. I then import each of them in a static Assets class which I use to access assets throughout my game. When I want to draw text of a certain size, I call a static method of my Assets class which takes the size I want to draw and gives me to closest BitmapFont from the atlas to the size that I want to draw.

Pros: Text looks pretty good, as long as you generate close to the sizes you need. You don't need to deal with gdx-freetype. Loading is fast, since it is just a single atlas (though it could be large). Cons: You the atlas can be very large. It takes some time to tweak the sizes you need in the atlas. When I add sizes to the atlas, I need to manually add them to the Assets class so they can be loaded (though you could possibly do something more clever to look through the region names and deduce what sizes are included).

The second is to use gdx-freetype to generate fonts as needed. In my Assets class I have a method which generates fonts of the size that is needed from a font file. I have a cache which I use to share previously-generated fonts for that size.

Pros: Text looks perfect on every size screen. Cons: Loading takes forever, which is especially bad if you use a font size for the first time in the middle of a game (huge lag). I generated font sizes at startup to hide this latency, but then I have a long loading screen to generate a bunch of fonts.

The third method I use is to use gdx-freetype to generate a small/medium/large font size scaled to the current display. I can then set scaling to get these the right size as-needed, and I can set texture filtering to make this not look bad. Since the fonts are scaled to the current screen, it looks pretty good across screen sizes.

Pros: Text looks pretty good. Doesn't take that long to load (only 2 or 3 fonts generated). Text scales with screen sizes gracefully. Cons: Text might not look perfect. Takes longer to load than a single atlas.
> 2 votes

---
Tags: libgdx, fonts
---


# Question
Title: How do I keep enemies from clumping up into one area?
I am making a zombie game and as I was making it I noticed the zombie AI starts to clump up into one mega zombie in one area. I was wondering how I could keep the zombies from doing that and instead make a horde like formation. I don't know how I would implement this and I don't know where to put it in my game logic so if you could give me some ideas or hints that would be fantastic.

Thanks in advance!

# Answer
> 0 votes
An easy solution for this is to make a list (for each zombie) of vectors, each representing the direction and distance to every other zombie. If the zombie has no other directives, add up all of the vectors in the its list and then make the zombie move in the opposite direction as the resulting vector.

Be sure to recalculate if the zombie must stop for any reason.

---
Tags: collision-detection, ai
---


title: Drawing Sprites with Artemis

text:
# Question
Title: Drawing Sprites with Artemis
I am trying to trace the `StarWarrior` code (the Artemis tutorial). I cannot figure out how these sprites are being drawn. This is the code where the player's ship is initialized:

```
/// <summary>The initialize player ship.</summary>
private void InitializePlayerShip()
{
    Entity entity = this.entityWorld.CreateEntity();
    entity.Group = "SHIPS";

    entity.AddComponentFromPool<TransformComponent>();
    entity.AddComponent(new SpatialFormComponent("PlayerShip"));
    entity.AddComponent(new HealthComponent(30));

    entity.GetComponent<TransformComponent>().X = this.GraphicsDevice.Viewport.Width * 0.5f;
    entity.GetComponent<TransformComponent>().Y = this.GraphicsDevice.Viewport.Height - 50;
    entity.Tag = "PLAYER";
}

```

Which line of code actually leads to the ship being drawn? The drawing takes place in `PlayerShip.cs`. Here is a commented version of the code with what I think is happening:

```
/// <summary>The initialize player ship.</summary>
private void InitializePlayerShip()
{
    Entity entity = this.entityWorld.CreateEntity(); //declare and initialize entity
    entity.Group = "SHIPS"; //Unused label

    entity.AddComponentFromPool<TransformComponent>(); //Add the component to store X and Y
    entity.AddComponent(new SpatialFormComponent("PlayerShip")); //Add a component which is just a String (perhaps this has something to do with PlayerShip.cs?)
    entity.AddComponent(new HealthComponent(30)); //Add a health component with 30 hp

    entity.GetComponent<TransformComponent>().X = this.GraphicsDevice.Viewport.Width * 0.5f; //Initialize the TransformComponent's X
    entity.GetComponent<TransformComponent>().Y = this.GraphicsDevice.Viewport.Height - 50; //Initialize the TransformComponent's Y
    entity.Tag = "PLAYER"; //Unused label
}

```

So how is the actual sprite being drawn? Because, I am not seeing it. :(

If it is being drawn by `entityWorld.Draw()` in the `Draw()` method, then which line(s) of code put it in the world to be drawn? Or what is actually happening in `entityWorld.Draw()`?

I believe the `RenderSystem` is the one that is doing the drawing, but I don't get how it is being called.

I am sorry for the uninformed question, but I have made no progress after about 12 hours, and I desperately need some guidance!

# Answer
> 2 votes
Each system in Artemis has a function called `process`, the `process` function in the RenderSystem looks like this:

```
@Override
protected void process(Entity e) {
    Spatial spatial = spatials.get(e.getId());
    Transform transform = transformMapper.get(e);

    if (transform.getX() >= 0 && transform.getY() >= 0 && transform.getX() < container.getWidth() && transform.getY() < container.getHeight() && spatial != null) {
        spatial.render(graphics);
    }
}

```

This is getting the `Spatial` component from each entity. The `Spatial` component defines the sprite to be rendered.

That sprite is then being drawn to screen with the `render` call you see above. Which looks like this:

```
@Override
public void render(Graphics g) {
    g.setColor(Color.green);
    g.setAntiAlias(true);
    ship.setLocation(transform.getX(), transform.getY());
    g.fill(ship);
}

```

---
Tags: sprites, entity-system, artemis
---


# Question
Title: Calculate point of circle–circle collision between frames
I need to find the exact XY coordinate where a circle collides with another circle calculated between frames. This means that I take the coordinate of the moving circle on the previous frame and take its coordinate on the current frame. Then I need to find the position where the circle collides some time along this line segment.

*In the diagram below, the blue circle moves from the previous frame (upper) to the current frame (intersecting, lower). During this time it would have hit where the dashed circle is. I need to find the coordinate of the green point.* *Also note that it may be possible for the blue circle to entirely pass through the red circle. There would then be two points, so the first must be used.*

# Answer
> 3 votes
Here's my idea (sorry for terrible picture, I've used `Paint` :P):

In the first picture you see a moving circle `#1` (red arrow is its moving direction) and a static circle `#2`. Red line is drawn along the `moving direction vector`. Let's say the moving circle's radius is `R1` and the static one's is `R2`. Circle `#1`'s center point is `C1` and the other one's is `C2`. Circle `#1`'s center point **after** moving is `C1'`.

In the second picture you can see the moment of collision. You can imagine a third circle `#3` \- one that has its center in the same point as circle `#2` (`C2`) and its radius equals `R1+R2`.

Now you calculate the `crossing points` of the red line and the circle `#3` (equate line's and circle's equations). The will give you `2` points (or `1` in a special case, or `0` if the circles actually don't collide). You should discard the point that is farther away from circle `#1`'s original center position (from the previous frame) - 'C1'.

Now you just calculate the point between circle `#2`'s center `C2` and the line-circle `crossing point` (`C1'`) calculated in the previous step - which is exactly `R2` away from circle `#2`'s center `C2`. You can do that easily by using `lerp` (linear interpolation): `collision_point = lerp(C2, C1', R2/(R1+R2))`. That is the 2 circles' `collision point` you wanted.

One more note - when you calculate all that on paper try to simplify/reduce the formulas - I didn't do that myself now but there's a good chance you end up with a nice concise formula.

And now that I think about it, it's actually a very important step - if I'm not mistaken, if you can bring all the transformations down to one formula and simplify it maximally, **you should get the optimal formula for calculating the collision point regardless of the method used to derive it**.

---
Tags: collision-detection, physics
---


title: How do I write a "Connect Four" AI?

text:
# Question
Title: How do I write a "Connect Four" AI?
I've made a *Connect Four* game. The first move is made by the player and the second by the computer. Currently, the computer moves randomly; its moves are generated by C++'s random number generator `rand()`. I'd like to build a basic AI that tries to win or prevent the player from winning.

How can I go about doing this?

# Answer
First, you need a rating function. A rating-function analyzes the playing field, rates which player currently appears to have a better chance of winning, and outputs it as a positive (computer has an advantage) or negative (player has an advantage) number.

You could calculate the rating by checking each already placed chip and see how many possible lines of four are still possible to complete with that chip and how complete they already are. When the chip belongs to the AI, add points for every possible line. When the chip belongs to the player, subtract the same amount of points. An already complete four-line would be a rating of +∞ or -∞, depending on which player has it (there is no better move than one which fulfills the win condition).

Then you use this function to calculate the rating of every currently possible AI move followed by every possible player response to that move (when your playing field has 8 columns and no columns are full, you would have to rate 64 possible outcomes). Then pick the AI move where the enemy response with the worst rating (from the PoV of the AI) is still rated higher than the worst-rated response of every other AI move.

A cheap way to make the AI stronger is to not just explore one round in the future but even more rounds. But keep in mind that the computation time will increase exponential. A much more efficient and elegant way, however, is usually to improve your rating function so the AI can make better strategic decisions.

This method is called the minmax algorithm, and it can be applied to any turn-based game without information hiding and a small number of possible moves each turn. The only thing you have to adapt to each game is the rating function. When the game has a large number of possible moves each turn, the performance can be enhanced through alpha-beta pruning (not following obviously bad tree branches).
> 7 votes

# Answer
I suggest you represent your game as a tree. This obviously mandates that you know basic graph theory. Google: BFS, DFS, graph theory - until you get the basic concepts such as node, leaf, children, parents, siblings, etc.

The initial game setting is the root node, its branches are the moves you can make, the other inner nodes are distinct game states that you get to by taking those moves, and leaf nodes are end states that can be `win`, `loss`, or `draw`.

Visualization of the game state tree:

Where #1 is the empty board, and #2 #7 #8 are the game states you get to from possible moves for the first player. Of course, the tree for Connect Four would look different.

Making a move simply means visiting a node, i.e. going by one of the branches. Please note that a single node presents the **entire** game state - i.e. it is a collection of **all** the game pieces and the entire board (obviously this can get memory-heavy, but there are optimizations).

You also have to use some stochastic and heuristic methods because the number of nodes will grow exponentially in size - you simply wont be able to traverse all of them and *know* which one to choose - statistics is your only weapon.

The Monte Carlo method seems to be suitable here.

When deciding which branch to take, you obviously have to pick the one with the highest probability of winning. So you have to calculate that probability for **each** of the possible branches (moves).

You do this by moving to them, and then picking random paths to go down. You continue down the paths until you reach a final state. Say you sample 10 000 final states. Then the probability of winning for that branch is `winning states / (losing states + draw states)`.

The paths have to be random. You do this by picking a random sample of children of a node and only visiting them. At one point down the tree you will have to take only a single random child of a node because picking even a small percentage is **still exponential.**

There are also options of dividing the result by the depth of the search since deeper searches are less relevant.

Please note that you have to take into account what the other player would do: some of his moves are more likely to be taken than others, see MiniMax.
> 3 votes

# Answer
As has been said, treat the moves as a tree.

However, since you say C++ you're running off local storage and thus I'm going to propose a different answer than trying to write a rating function.

Instead, as has been said, the game has been solved. There are only 4.5 trillion possible boards and the fact that the AI doesn't want to make stupid moves takes out a bunch of them. Given some precalculation combined with modern processors this makes me think it should be possible to make the theoretically perfect move in all situations.

To do this you'll need to start out processing *EVERY* board on your machine. This will of course be quite slow. Save the first 11 moves of this tree in a form of your response to each of his possible moves. (Note: This can be packed into 20 bits per move, the resulting file is in the tens of megabytes.)

I think this puts you far enough into the game that you can now brute force it faster than a human would play. Code optimization will matter!
> 1 votes

---
Tags: ai
---


# Question
Title: Loading chunks of the terrain relative to the player's position
I'm making a small voxel-based multiplayer WebGL game with a Node.JS server which handles player positions and sends terrain chunk data to the clients. This is an example of how I'm currently sending the chunks:

```
var viewDistance = 6;

for (var x = playerPosX - viewDistance; x < playerPosX + viewDistance; x++)
for (var z = playerPosZ - viewDistance; z < playerPosZ + viewDistance; z++)
for (var y = playerPosY - viewDistance; y < playerPosY + viewDistance; y++) {
    client.send( getChunk(x, y, z) );
}

```

This simply loads and sends the chunks within the view distance, however I'm looking for a way to prioritize sending the chunks nearest to the player first. Obviously it's no good loading chunks that are far away before loading the one the player is standing on.

Assuming `playerPosX`, `playerPosZ` and `playerPosY` store the positions of the player and `client.send( getChunk(x, y, z) )` will send the chunk, does any one have any ideas how I would do this? Thanks.

# Answer
I would do something like this:

```
    var vd = 6; //view distance
    var v = vd*2+1; //length of cube of chunks we want to send
    var s = new Array(v*v*v); //used to store which chunks we have sent
    for(var i=0; i<s.length; ++i) { s[i] = false; }
    for(var i=0; i<=vd; i++){ //start at center and move out layer by layer
        for(var x=-i; x<=i; x++){ //get all chunks inside current layer
            for(var y=-i; y<=i; y++){
                for(var z=-i; z<=i; z++){
                    if(!s[(x+vd)+(y+vd)*v+(z+vd)*v*v]){ //exclude already sent chunks
                        client.send( getChunk(x+plX, y+plY, z+plZ)); //send chunk
                        s[(x+vd)+(y+vd)*v+(z+vd)*v*v]=true; //mark chunk as sent
                    }
                }
            }
        }
    }

```

I may have made a mistake somewhere since I've never used JavaScript before, but I think the comments should make it clear what I mean.

This assumes your player doesn't move off of the current chunk while while the loop is in progress, if that's possible you would need to either restart the loop or use some other method for storing which chunks you have already sent to the client.
> 3 votes

# Answer
Split the loading into sections (the white chunk is the one you are standing on). The above image shows the x and y axes, with the z axis left to your imagination.

Begin by sending the white chunk (playerPosX, playerPosY, playerPosZ). After that start moving outward along each axis, in both directions (+x, -x, +y, -y, +z, -z). Going outward, along each coloured section (+x, -x, +y, -y):

```
Distance 1: send 2 x 2 chunks
Distance 2: send 4 x 4 chunks
Distance 3: send 6 x 6 chunks

```

Along the +z section:

```
Distance 1: send 3 x 3 chunks
Distance 2: send 5 x 5 chunks
Distance 3: send 7 x 7 chunks

```

-z section:

```
Distance 1: send 1 x 1 chunks
Distance 2: send 3 x 3 chunks
Distance 3: send 5 x 5 chunks

```

As (pseudo) code:

```
sendChunk(playerPosX, playerPosY, playerPosZ);

for (var i = 1; i < distance; i++) {
    //Green
    for (var y = 0; y < i * 2; y++) {
        for (var z = 0; z < i * 2; z++) {
            sendChunck(playerPosX - i,
                       playerPosY + (i - 1) - y,
                       playerPosZ + (i - 1) - z);
        }
    }

    //Do the same for yellow, blue, red, with different axes
    //Do (almost) the same along +z and -z
}

```

You could also further improve the solution by starting from the center of each "layer" you send, using the exact same technique of sectioning. The image above could represent a 7 x 7 layer being sent.

The resulting code won't be very concise, but you will only be iterating through each chunk a single time, making it of time complexity O(n).
> 3 votes

---
Tags: javascript, voxels, webgl, terrain-rendering
---


# Question
Title: Which nodes of the Collada DAE are most relevant for game object/character use?
**I'm really new to game dev / D3D.** And I was looking to choose an intermediary format to work with and convert to my internally used format. Collada DAE seems to be good as it can export animation too and it's XML. Kind of bloated but easy to parse.

My expertise is in reusable code writing, libraries, APIs and such. **So my first impulse was to go an implement a FULL parser of the Collada format** given the fact that I'm not 100% what I need or will need to extract from it.

As it seems Collada is trying to be everything and the kitchen sink, **there's definitely stuff in there I don't think I need to be concerned about.** So, sanity prevailed and decided to come here and ask the experienced people **what are the important nodes for game characters and objects in the `.DAE` file? Or is there another format considered friendlier by game devs that can export animations too?**

I've **figured out the following are important**:

* geometries *(mesh + triangles)*
* materials + images
* animations + controllers
* visual scenes + scene

**What else am I missing from the top-level node list?** I don't think lights are important as I deal with that in code. I just need to import meshes + textures + animations. At least for now, as I'm just starting out in D3D programming.

For a non-animated object I can get away with a `.OBJ` file but for a player with animations, I really don't think `.OBJ` supports them.

> So the question is: **Which DAE nodes are relevant to game objects and animated characters?**... *and if someone experienced consuming this format could provide a few words describing them, in a more game-friendly way then that specification... would be great!* Or should I use another intermediary format but `.DAE`?

# Answer
> 0 votes
Well I got the answer I was looking for on `SO`:

> **Step by Step Skeletal Animation in C++ and OpenGL, Using COLLADA:**

*It's quite detailed. Leaving aside the `OpenGL` stuff, the explanations are really good.*

---
Tags: 3d, directx, skeletal-animation, character, collada
---


# Question
Title: Alpha Blending: use the pixel with the smallest alpha
I'm writing a transparency shader where I need any intersecting textures to, wherever they overlap, take the texture pixel with the smallest alpha value and render only that, discarding the other pixel(s).

Turn this:

Into this:

In pseudocode, something along the lines of…

```
if ( newPixel.alpha < currentPixelInFrameBuffer.alpha )
    currentPixelInFrameBuffer = newPixel;

```

I can't seem to find if there is a native alpha blending command that will do this. There exists `DstAlpha`, which is an alpha blending property that compares against the current fragment's frame buffer source alpha value, but I obviously cannot use that in the following manner…

```
AlphaTest Less DstAlpha

```

I've found there's a BlendOp Min, which is supposed to "Use the smaller of source and destination." but I can't seem to get that to work and I can't find documentation on what it means by 'smaller'.

# Answer
To get the RGB values of your scene influenced by the minimum of several alpha values from your fog, the most straightforward way to use a render texture. This requires Unity Pro.

**\[Edit: Unity 5 now allows the use of render textures in the free version as well. Yay! :D \]**

(Some alternatives are provided below if this isn't an option)

Set up a second camera, with Culling Mask set so that it sees only your fog hole quads. Set its Background to the colour you want your fog to be, and set its Depth so that it renders before the rest of your scene.

Then place a quad with this texture in front of your scene, so that it's visible to your main camera, and it should render on top as expected.

Set your fog hole shader to use:

```
BlendOp Min
Blend One One

```

and output all-white for the colour channel. (Either by using a .tga for your fog hole texture that's all white on the colour planes, or via the shader). This ensures the holes will never modify the fog colour, only its alpha.

Alternatively, you can make the RenderTexture in code with only a single channel, and apply any colour adjustment you want when you blend the finished fog into your scene. The advantage of rendering it as a full-colour map is mainly Editor convenience, and the ability to render arbitrary content into it like roiling clouds for the holes to later punch-out.

The reason compositing directly to your frame buffer without an intermediate texture won't work is that, as soon as that first quad is drawn, the RGB values of your scene in the dark region have already been modified. A quad drawn over it later with a lighter patch can't undo that change (at least not without dividing by DstAlpha, which is not one of the available operations).

If you're not able to use RenderTextures, your next best bets are:

1. changing your visual style so the fog isn't one even shade. That way you can just stamp down dark fog quads everywhere outside the main view, rather than punching holes inside it.
2. using the Mesh class to construct a one-layer piece of geometry that can be rendered for your fog without the same texel being blended over multiple times. One straightforward way to do this is a grid with vertex colours indicating visible/obscured cells, and a fragment shader that uses a noise texture to bias this value to keep the edge rough & feathery.

Edit: here's an example of suggestion #2, quickly mocked-up with an 8x8 vertex grid blended over a happy face reference texture.
> 3 votes

---
Tags: unity, shaders, glsl, transparency, cg
---


title: glOrtho setting view

text:
# Question
Title: glOrtho setting view
I am duplicating this thread from stackoverflow, please remove it if that is not allowed.

I'm completely new in OpenGL. I have this problem: I have quite a complicated scene, and I am looking at it from the front (default camera position). The way I have seen to move the camera is using the gluLookAt() function to set the point you want to look at, and glTranslate3f() to move the camera position. I need to move the camera with different data - my data is not the point I want to look at - rather, I have the data of the projection plane - determined with a viewing vector and a point in the plane. Is there a way to set the camera using this data rather than a "look at" point?

I am using an ortographic projection (glOrtho()), so everything is projected onto the projection plane.

UPDATE: To be more precise: the point I have is a point in the plane, to which I want to project to. I have in fact not only the plane, but the square to which I need to project, defined. So I have a scene somewhere a space, and a square somewhere away from that scene. I want to project the scene to that square and show that projection on screen. I hope that made it a bit clearer what I need to achieve ... While gluLookAt defines a point in the scene at which to look at, and the position of the eye. While eye is one point in space and projection offers perspective, with ortographic projection, you do not have one point, you have a whole square on which to project to, so how can I define that?

For easier understanding what I am trying to achieve. Here is the image of what glOrtho normally does:

Here is an image of what I am trying to achieve:

# Answer
I think, you need to multiply rotation matrix by projection. You can try building quaternion based rotation matrix or by euler angles. Then just do mvp\_matrix = rotation\_matrix * projection\_matrix.
> 0 votes

---
Tags: opengl
---


title: Layer depth problem

text:
# Question
Title: Layer depth problem
I try to create Puzzle JigSaw,and I want to display the selected piece on the first layer, the pieces that are on the original positions(solved) on the last layer and the others on the middle.

I select a piece on the Update method

```
public void Update(GameTime gameTime)
     {

        var touchLocation = InputManager.Instance.GetTouchLocation();

        if (touchLocation != null && touchLocation.Value.State == TouchLocationState.Pressed)
        {
            // select a piece
            SelectPiece(touchLocation.Value.Position);
        }
        if (touchLocation != null && touchLocation.Value.State == TouchLocationState.Moved && _selectedPiece != null)
        {
            // move the selected piece
            TouchLocation prevTouchLocation;
            touchLocation.Value.TryGetPreviousLocation(out prevTouchLocation);
            var distance = touchLocation.Value.Position - prevTouchLocation.Position;
            _selectedPiece.Position += distance;

        }
        if (touchLocation != null && touchLocation.Value.State == TouchLocationState.Released &&
            _selectedPiece != null)
        {
            var rec = _selectedPiece.OriginalCollisionRectangle;

            rec.Inflate(30,30);
            if (rec.Contains(_selectedPiece.CollisionRectangle))
            {
                _selectedPiece.Position = _selectedPiece.OriginalPosition;
                _selectedPiece.IsOnOriginalPosition = true;

            }
            _selectedPiece.IsSelected = false;
            _selectedPiece = null;

        }

```

Code used to select the piece

```
   public void SelectPiece(Vector2 currentSelectPosition)
    {
        foreach (var aPiece in PuzzlePieces)
        {
            if (aPiece.CollisionRectangle.Contains((int)currentSelectPosition.X, (int)currentSelectPosition.Y)&& !aPiece.IsOnOriginalPosition)
            {

                    _selectedPiece = aPiece;
                    _selectedPiece.IsSelected = true;
                    return;

            }
        }

    }

```

I used this code for drawing:

```
   public void Draw(SpriteBatch batch)
    {

        batch.Begin();

        foreach (var aPiece in PuzzlePieces.Where(apiece=>apiece.IsOnOriginalPosition&&!apiece.IsSelected))
        {
            aPiece.Draw(batch);
        }
        foreach (var aPiece in PuzzlePieces.Where(apiece => !apiece.IsOnOriginalPosition && !apiece.IsSelected))
        {
            aPiece.Draw(batch);
        }
         if (_selectedPiece != null)
        {
            _selectedPiece.Draw(batch);
        }

       batch.End();

    }

```

This code work fine, but i have display problem, when I selected a piece,the piece that behind this piece is selected.

Could you help me please?

Thanks

# Answer
In SelectPiece(), don't return right away when you find a piece that contains the selection position. For all we know, that piece is at the bottom of a stack.

Instead, keep track of that piece as your "best candidate so far," then keep checking other pieces. If you find another piece, check whether it's in front of the best candidate you've found so far. If so, replace your best candidate with this piece, otherwise keep searching.

Mark the best candidate as selected only once you've checked all selectable pieces that could overlap the selection position.

At the end of the function you're guaranteed to have the **frontmost** piece whose bounds include the selection position, instead of just *any* piece whose bounds include the selection position.
> 0 votes

# Answer
XNA has a depth option when drawing with a SpriteBatch.

This is the command I use for drawing:

```
Batch.Draw(sprite.Sheet.Texture, sprite.Position, sprite.Sheet.GetSourceRect(sprite.SpriteX, sprite.SpriteY), sprite.Color, sprite.Rotation, sprite.Origin, sprite.Scale, SpriteEffects.None, sprite.Depth);

```

My `sprite` is a class which contains a couple of properties about a sprite. Depth can be 0.0 to 1.0, where 0.0 is background and 1.0 is foreground. You need to use FrontToBack or BackToFront sprite sorting in your `Batch.Begin(...);` call for this to work though.

You can of course change this to your needs, MonoDev and Visual Studio should show the different overloaded parameter lists, so you can tinker with those to your needs.
> 3 votes

---
Tags: monogame, depth-buffer, puzzle
---


title: Background color gradient with SDL

text:
# Question
Title: Background color gradient with SDL
I want to create a menu for a game using a color gradient as the background. Is there a way to create a gradient background instead of using an image for it (since I don't know what size the window will be, using an image is no option).

Please note: I need to achieve this using only the C standard library and the SDL, no other library and no C++.

# Answer
> 4 votes
See this StackOverflow answer: There is no ready-made way in SDL, so you will have to manually create the gradient by computing the color for each line and drawing it. More details in the linked answer.

Some additional inspiration can be drawn from the following two threads on gamedev.net:

1. SDL Gradient
2. Better Gradients

Regarding the image & window size argument: You could probably use an precomputed gradient image and make it stretch to the current window size. That would probably be faster from a performance point of view and still be able to handle all window sizes.

---
Tags: sdl, c, interface
---


# Question
Title: Using a vector to store multiple instances of a class
To warm up with SMFL, I am creating a simple Block Breaker game. For the blocks and balls, I would like to store them as "instances" in a vector so that they can be added/removed with ease.

However, the compiler spits out an error when attempting to access the vector.

block.h

```
class Block {
private:
    bool dead;

public:
    Block();
    bool isDead();
    static std::vector<Block*> blockList;

    float x;
    float y;
};

```

main.h

```
#include "Block.h"

Block playerBlock;

```

main.cpp

```
#include "main.h"

int main()
{
    playerBlock.x = 50;
    playerBlock.y = 20;
    Block::blockList.push_back(&playerBlock);
    return 0;
}

```

When compiling, Xcode spits out the following error: Undefined symbols for architecture i386: "Block::blockList", referenced from: \_main in main.o ld: symbol(s) not found for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any help is welcome. This is not all of my src but it is all of the src related to the problem at hand.

# Answer
> 1 votes
In order to get your code working, you have to add the following initialization statement for your `Block::blockList`. In your case, it has to be in `main.cpp` (or your `block.cpp` if that does exist), since it needs to be outside of the class declaration for all static members (other than some integral types such as `int`):

```
std::vector<Block*> Block::blockList;

```

Some links to similar questions:

# Answer
> 1 votes
You declared your static member only in a header file, but now you need to actually define it in an implementation file. So in your main.cpp, below the #include, add:

```
std::vector<Block*> Block::blockList;

```

Some side notes:

1. Defining the static member should happen only in 1 translation unit (~= .cpp file)
2. Be cautious with static members as their initialisation order is undefined, so once you start adding them all over the place and putting one inside the other, things may/will go haywire at some point.
3. You're storing "naked" pointers in the vector, which is valid but as your program expands you will run into ownership issues (i.e. who is in charge of maintaining/deleting what memory?) so you will want to look into std::shared\_ptr and/or std::unique\_ptr sooner rather than later.

std::shared\_ptr http://en.cppreference.com/w/cpp/memory/shared\_ptr std::unique\_ptr http://en.cppreference.com/w/cpp/memory/unique\_ptr

Keep all of your blocks in one single std::vector\> for example and keep shared\_ptr or weak\_ptr references to them where appropriate. Aside from the reference links read up a bit on examples of shared\_ptr online, e.g. https://stackoverflow.com/questions/3476938/example-to-use-shared-ptr

Good luck!

---
Tags: c++, vector
---


title: How can I modify PlayStation 1 games?

text:
# Question
Title: How can I modify PlayStation 1 games?
Is it possible to modify Sony PlayStation 1 games?

For example I'm planning to modify a soccer game called *Winning Eleven 3*. What I'm exactly trying to modify is player properties such as speed, shot power and so on.

# Answer
No, you can't really do this.

First of all, PlayStation 1 games were shipped on CD, which is read-only media. By definition you can't write to it, so modifications are out of the question.

So you may be thinking that you could grab an emulator and a CD image and modify that, but again you're stuck. You don't have the source code to the game, you don't have a PlayStation 1 development kit, and even if you did, you may be missing certain other tools and libraries that the original authors used.

So you can't write to the CD, you can't rebuild the game, you're stuck with trying to hex-edit a CD image file on your hard disk and running that through an emulator. I suppose you could call that "modifying", for certain definitions of "modifying"; you may be able to change a few constants or nop out a few instructions, but it's a process of trial and error (and the trial will be farcical, the errors comedic).

If you've ambitions to modify a game, then you're going to be better off choosing a game that's set up to be modified in the first place, and using a platform that enables modification.
> 6 votes

# Answer
I have done this, though it's not by any means simple. I'm working on a modification for the PSX NTSC release of Final Fantasy VII, 'Rebirth', that involves some minor changes to battle logic.

Generally speaking the procedure is to

1. Find the executable or overlays (this takes some reversing; you basically just have to watch for big chunks of data being streamed into a location and then executed). If you're unlucky, the executable will be compressed, so you'll need to reverse the compression too.
2. Use an emulator debugger to discover the values that are relevant to the logic, then use breakpoints and watch expressions to see where they are being manipulated. After a lengthy reversing process, you should be able to find your logic with a disassembler.
3. Reverse the assembler. Whilst a decompiler might provide some limited help, you will probably have to do this manually. This is quite hard unless others have done a lot of groundwork already.
4. Rewrite the logic, usually in assembler (MIPS series 1). This is actually probably the easiest step if you're already a programmer. ARMIPS is a good assembler and works for both the PSX and N64.
5. Insert your content (ARMIPS can do that for you) and reinsert the file. You're going to want to insert the file with something that doesn't tread on the filesystem or ECC data.
6. Test your logic. If there are bugs, repeat steps 4-5 until everything works.
7. Distribute your mod as a patch file of some sort (PPF is the most common one) and get fan mail from all over the globe (by which I mean rude emails complaining about your changes).
> 15 votes

---
Tags: modding, editors, source-code
---


title: Relative Position/Rotation calculation

text:
# Question
Title: Relative Position/Rotation calculation
I have 2 objects each with a 3x3 Matrix (Orientation) and a Vector3 (Translation). Both are relative to world coordinates.

How do I calculate the position and orientation of object B in relation to object A?

I'm using the JVector, JMatrix that are a part of the Jitter3D physics library. (http://code.google.com/p/jitterphysics/)

Any help would be greatly appreciated!

# Answer
For the matrix, you multiply them to combine rotations:

so if using row Major matrices:

```
someUnknownRotationMatrix * OrientationA  = OrientationB

```

then: `someUnknownRotation` represents the **orientation of object B in relation to object A**

so, using basic math principles (divide both sides by OrientationA):

```
someUnknownMatrix = MatrixB * inverse(MatrixA)

```

## -

Similar with the position:

```
Vector3 someUnknownVector;//represents position of object B in relation to object A

positionA + someUnknownVector = positionB
//then after applying similar math principles(subtract positionA from both sides):
someUnknownVector = positionB - positionA

```
> -3 votes

---
Tags: physics, matrix, vector, orientation
---


title: Render two images to an SDL_window

text:
# Question
Title: Render two images to an SDL_window
I want to create a menu for an SDL game, so I load an Image to an SDL\_Window as the background, then I try to load the next image which will be a button but it doesn't display the button to the window, it just displays the background.

I'm a newbie so perhaps it is an obvious mistake.

Here's what I got:

```
#include <stdio.h>
#define SDL_MAIN_HANDLED
#include "SDL.h"

int main(int argc, char *argv[])
{
    int a = 1;
    SDL_Event event;

    SDL_Window* window;
    SDL_Surface* background_surface;
    SDL_Texture* background_texture;
    SDL_Renderer* background_renderer;
    SDL_Surface* button_surface;
    SDL_Texture* button_texture;
    SDL_Renderer* button_renderer;

    SDL_Rect button_pos;
    button_pos.h = 65;
    button_pos.w = 320;
    button_pos.x = 0;
    button_pos.y = 0;

    SDL_Init(SDL_INIT_VIDEO);
    window = SDL_CreateWindow(
        "Cosmic Racing",
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        320,
        568,
        SDL_WINDOW_OPENGL
    );
    background_renderer = SDL_CreateRenderer(window, -1, 0);
    background_surface = SDL_LoadBMP("Background.bmp");
    background_texture = SDL_CreateTextureFromSurface(background_renderer, background_surface);
    SDL_RenderCopy(background_renderer, background_texture, NULL, NULL);
    SDL_RenderPresent(background_renderer);

    button_renderer = SDL_CreateRenderer(window, -1, 0);
    button_surface = SDL_LoadBMP("Play.bmp");
    button_texture = SDL_CreateTextureFromSurface(button_renderer, button_surface);
    SDL_RenderCopy(button_renderer, button_texture, &button_pos, NULL);
    SDL_RenderPresent(button_renderer);

    while(a)
    {
        SDL_PollEvent(&event);
        if(event.type == SDL_QUIT)
        {
            a = 0;
        }
    }

    SDL_DestroyTexture(button_texture);
    SDL_FreeSurface(button_surface);
    SDL_DestroyRenderer(button_renderer);
    SDL_DestroyTexture(background_texture);
    SDL_FreeSurface(background_surface);
    SDL_DestroyRenderer(background_renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

```

BTW if you find additional mistakes please tell me. Thank you ;)

# Answer
You should use ONE renderer for your rendering needs. Please don't use two.

Don't use the OpenGL flag if you are not going to use it!

For the SINGLE renderer, I am assuming you want gpu rendering so replace the 0 in the last argument in `SDL_CreateRenderer()` and replace it with `SDL_RENDERER_ACCELERATED`.

Here is the fixed source code, Used some random images to test it and works fine, also please dont `#include <stdio.h>` when you are never using it in this code. Please don't leave those pointers unassigned! Please always `NULL` them when you initialize them to avoid issues and future bugs. Also place the `SDL_RenderCopy()` & `SDL_RenderPresent()` in the very end of your `while` loop to avoid future issues I am predicting you will have. Also added `SDL_RenderClear()` just to make the code more future proof (lol). Also in `SDL_RenderCopy(renderer, button_texture, &button_pos, NULL)` you did it wrong, it should be `SDL_RenderCopy(renderer, button_texture, NULL, &button_pos);`

```
#define SDL_MAIN_HANDLED
#include "SDL.h"

int main(int argc, char *argv[])
{
int a = 1;
SDL_Event event;

SDL_Window* window = NULL;
SDL_Surface* background_surface = NULL;
SDL_Texture* background_texture = NULL;
SDL_Renderer* renderer = NULL;
SDL_Surface* button_surface = NULL;
SDL_Texture* button_texture = NULL;

SDL_Rect button_pos;
button_pos.w = 320;
button_pos.h = 65;
button_pos.x = 0;
button_pos.y = 0;

SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow(
    "Cosmic Racing",
    SDL_WINDOWPOS_CENTERED,
    SDL_WINDOWPOS_CENTERED,
    320,
    568,
    SDL_WINDOW_SHOWN
);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
background_surface = SDL_LoadBMP("Background.bmp");
background_texture = SDL_CreateTextureFromSurface(renderer, background_surface);

button_surface = SDL_LoadBMP("Play.bmp");
button_texture = SDL_CreateTextureFromSurface(renderer, button_surface);

while(a)
{
    SDL_PollEvent(&event);
    if(event.type == SDL_QUIT)
    {
        a = 0;
    }
    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, background_texture, NULL, NULL);
    SDL_RenderCopy(renderer, button_texture, NULL, &button_pos);
    SDL_RenderPresent(renderer);
}

SDL_DestroyTexture(button_texture);
SDL_FreeSurface(button_surface);
SDL_DestroyRenderer(renderer);
SDL_DestroyTexture(background_texture);
SDL_FreeSurface(background_surface);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}

```
> 3 votes

---
Tags: sdl, c, image, interface
---