title: Large Sprite Performance

text:
# Question
Title: Large Sprite Performance
I've got a large Sprite generated using a set of vertices(x,y coordinates) and a bitmap pattern (using moveTo, lineTo, beginBitmapFill, endFill ...etc). It's about 15000 pixels wide and between 1500 - 2000 pixels high depending on the level -it's the terrain for a 2D game.

My question is: what is the best way to display/move it on the stage - performance wise?

Currently I'm just adding it to the stage as is...I get decent frame rate/ memory/ cpu usage but I want to optimize it for slower PCs. Any ideas? I've been reading a little about blitting but I'm not sure how to implement it in my case.

Thanks.

# Answer
> 0 votes
**I was thinking about this and finally realized your problem with performance is drawing alone - you redraw whole screen everyframe when terrain is scrolled, that's an overkill for weak CPU. And that's where Starling makes miracles.**

I'm not sure how well flash optimizes it behind scenes, it changes a lot with time (notice that in every update there is "significantly increased performance" or something like that), for example, nowadays blitting don't give you as much as it used to years ago.

I think the most up-to-date solution to spare CPU is to use GPU, that is stage3D. I know, I know, your game is 2D, but stage3D is just about GPU (graphics-card) rendering. There is Starling 2D framework, that uses stage3D. But you should know that you can't draw vector graphics below stage3D (you can only draw them on top of GPU rendered graphics, unless you draw them to a bitmap, rasterizing it, and then use in Starling)

Other solutions are to divide the bitmap to smaller parts, or as you said - blitting, that is using copyPixels method.

# Answer
> 1 votes
Edit: I think I misread your question. I thought you were asking for a looping background. In case you might find this useful anyways I'll my answer here. Correct me if I'm wrong though!

You can either create a bitmap with a resolution of your stage size and process the edges to loop ( takes a bit a of a script for this but they are out there).

Or you create 9 sprites/bitmaps that are repositioned depending on the cameras position. Creating an illusion of endless loops.

I hope this makes any sense:

Direction is the movement of your camera, thus the position of the camera changes.

The base is the center of your camera or character ( if it's in the center at least). So basically you define the position of each background piece by dividing the position by the width and height of the screen

```
 var baseX:int = int(center.x / cellWidth) * cellWidth; // Ensures a clean integer;
 var baseY:int = int(center.y / cellHeight) * cellHeight;

```

Now you loop trough your sprites/bitmaps with a double forloop( because you are working with rows here)

I might have made a mistake but it looks something like this

```
for (var y:int = 0; y < 3; y++)
{
    //Each column
    for (var x:int = 0; x < 3; x++)
    {
        bitmaps[y][x].x = baseX + (y * cellWidth); // Cell width and height
        bitmaps[y][x].y = baseY + (x * cellHeight);// are the sizes of the pieces
    }
}

```

Use a 2D array, it's easier due to the nature of your rows and columns.

Here is an example of a 4x4 grid. Obviously the cells are suppose to be bigge so that you don't see them jump around:

4x4 example

Use arrow keys.

---
Tags: flash, actionscript-3
---


# Question
Title: 2D SAT How to find collision center or point or area?
I've just implemented collision detection using SAT and this article as reference to my implementation. The detection is working as expected but I need to know where both rectangles are colliding.

I need to find the center of the intersection, the black point on the image above. I've found some articles about this but they all involve avoiding the overlap or some kind of velocity, I don't need this.

I just need to put a image on top of it. Like two cars crashed so I put an image on top of the collision. Any ideas?

**## Update**

The information I've about the rectangles are the four points that represents them, the `upper right`, `upper left`, `lower right` and `lower left` coordinates. I'm trying to find an algorithm that can give me the intersection of these points.

# Answer
> 1 votes
You dont actually want the center of collision, generally. The term to look for is "polygon clipping." I'll try to give a quick description.

The idea is to clip one polygon's edges against the incident edge (the axis you separated on), as well as the edge's ends. The clip points you end up with (usually two) will be the contact points to use for physics. You can join these with any interior vertices in the collision if you need a shape rather than just points, by you generally don't need that.

---
Tags: 2d, collision-detection, separating-axis-theorem
---


title: Detecting a ledge in Box2D

text:
# Question
Title: Detecting a ledge in Box2D
> **Possible Duplicate:**
> Detect Open Space in Farseer
> How do I detect ledges?

I'm making a 2D platformer with Box2D. The player needs to be able to grab onto a ledge and pull him/herself up.

Right now I have a sensor that extends in every direction from the upper half of the player's body.

The logic seems simple enough: if there are tiles inside the sensor and empty space above them, then it's a ledge and the game should act accordingly. The problem is that I can't figure out how to implement that logic with Box2D.

Anyone have any ideas?

# Answer
What I needed to do was have two sensors. One extending outward of the upper half of the body, one with the exact same dimensions right above it.

If the top sensor isn't colliding with anything, and the bottom sensor is, it's a ledge.
> 4 votes

# Answer
Since no one has answered, check here. It should be the same

http://www.box2d.org/forum/viewtopic.php?f=3&t=7352

http://www.iforce2d.net/b2dtut/sensors
> 2 votes

---
Tags: 2d, box2d, physics, platformer
---


# Question
Title: How to I get a rotated sprite to move left or right?
Using Java/Slick 2D, I'm using the mouse to rotate a sprite on the screen and the directional keys (in this case, WASD) to move the spite. Forwards and backwards is easy, just position += cos(ang)\*speed or position -= cos(ang)\*speed. But how do I get the sprite to move left or right? I'm thinking it has something to do with adding 90 degrees to the angle or something. Any ideas?

Rotation code:

```
int mX = Mouse.getX();
        int mY = HEIGHT - Mouse.getY();
        int pX = sprite.x+sprite.image.getWidth()/2;
        int pY = sprite.y+sprite.image.getHeight()/2;
        double mAng;

        if(mX!=pX){
            mAng = Math.toDegrees(Math.atan2(mY - pY, mX - pX));
            if(mAng==0 && mX<=pX)
                mAng=180;
        }
        else{
            if(mY>pY)
                mAng=90;
            else
                mAng=270;
        }

        sprite.angle = mAng;
        sprite.image.setRotation((float) mAng);

```

And the movement code (delta is change in time):

```
Input input = gc.getInput();

                Vector2f direction = new Vector2f();
                Vector2f velocity = new Vector2f();

                direction.x = (float) Math.cos(Math.toRadians(sprite.angle));
                direction.y = (float) Math.sin(Math.toRadians(sprite.angle));
                if(direction.length()>0)
                    direction = direction.normalise(); //On a separate note, what does this line of code do?

                velocity.x = (float) (direction.x * sprite.moveSpeed);
                velocity.y = (float) (direction.y * sprite.moveSpeed);

                if(input.isKeyDown(sprite.up)){
                    sprite.x += velocity.x*delta;
                    sprite.y += velocity.y*delta;
                }if (input.isKeyDown(sprite.down)){
                    sprite.x -= velocity.x*delta;
                    sprite.y -= velocity.y*delta;
                }if (input.isKeyDown(sprite.left)){
                    //???
                }if (input.isKeyDown(sprite.right)){
                    //???
                }

```

# Answer
> 1 votes
If you want the sprite to face the right or left you can add or subtract rotation and move forward. So I'd move your input checking for left/right to somewhere before you calculate the direction:

```
if (input.isKeyDown(sprite.left)){
     sprite.angle -= turnSpeed;
}if (input.isKeyDown(sprite.right)){
     sprite.angle += turnSpeed;
}

```

Though, you'll have to change some things with your code, because this will likely get reset as soon as the mouse moves or you update from the mouse position again.

However, if you want more of a strafe action (facing forward and "side-stepping"), you'll want to find the vector that's perpendicular to your forward vector and move along that.

```
moveDirLeft = new Vector2f(-direction.y, direction.x)
moveDirRight = new Vector2f(direction.y, -direction.x)

```

Swap the x and y, then choose one to be negative depending on which direction you want to go.

This new direction should be calculated before you update the velocity. Use the new direction to update the velocity if the new direction has been updated, otherwise just use the current heading as you are now.

---
Tags: java, sprites, rotation, movement, slick
---


# Question
Title: How do I make a moving object stop smoothly at the end of a path?
There are a dozen ways I could word this question, but to keep my thoughts in line, I'm phrasing it in line with my problem at hand.

So I'm creating a floating platform that I would like to be able to simply travel from one designated point to another, and then return back to the first, and just pass between the two in a straight line. However, just to make it a little more interesting, I want to add a few rules to the platform.

1. I'm coding it to travel multiples of whole tile values of world data. So if the platform is not stationary, then it will travel at least one whole tile width or tile height.
2. Within one tile length, I would like it to accelerate from a stop to a given max speed.
3. Upon reaching one tile length's distance, I would like it to slow to a stop at given tile coordinate and then repeat the process in reverse.

The first two parts aren't too difficult, essentially I'm having trouble with the third part. I would like the platform to stop exactly at a tile coordinate, but being as I'm working with acceleration, it would seem easy to simply begin applying acceleration in the opposite direction to a value storing the platform's current speed once it reaches one tile's length of distance (assuming that the tile is traveling more than one tile-length, but to keep things simple, let's just assume it is)- but then the question is what would the correct value be for acceleration to increment from to produce this effect? How would I find that value?

# Answer
Using these steering behaviors as a guide. Looking at the arrive behavior:

> Arrival behavior is identical to seek while the character is far from its target. But instead of moving through the target at full speed, this behavior causes the character to slow down as it approaches the target, eventually slowing to a stop coincident with the target.

We can create an "arrive at" function like something similar to this:

```
arriveAtPoint(Vector2f position, Vector2f target) {
    float slowing_distance = 1;
    Vector2f target_offset = target - position;
    float distance = target_offset.length();
    float ramped_speed = currentVelocity * (distance / slowing_distance);
    float clipped_speed = Math.min(ramped_speed, currentVelocity);
    targetLinearVelocity = target_offset.scale(clipped_speed / distance);
    acceleration = targetLinearVelocity -linearVelocity;
}

```

This will update the acceleration we need to use to apply to the object in motion.
> 6 votes

# Answer
Take a look at this page: http://sol.gfxile.net/interpolation/index.html

It seems that you want a effect just like the smoothstep:

If you have leftmost point, the rightmost point the platform should achieve, and the time it should use to go make a full sequence, something like this may be ok:

foreach frame:

```
float smoothstep(float t, int level = 1)
{
    float ret = t;
    for(int i = 0; i < level; ++i)
    {
        ret = pow(ret, 2) * (3 - 2 * ret);
    }
    return ret;
}

currentTime += deltaTime;
if(currentTime > fullTime) currentTime -= fullTime;
float halfTime = fullTime / 2.0;
float t = abs(currentTime - halfTime) / halfTime;
t = smoothstep(t, 1);
platformPosition = rightPoint * t + leftPoint * (1 - t);

```

if you're using a physics engine, you can make it with impulses, shouldn't be that hard to translate. If you want a even smoother process, you can increase the smoothstep level.
> 5 votes

# Answer
You can use XnaTweener that provides easing functions that interpolate values from one point to another in a easy way...

Here is a reply with some code based in the Xna Tweener project and a video showing how it performs...

https://gamedev.stackexchange.com/a/26872/8390

\[EDIT\]

You should have a sequence of keys that defines the platform movement, like this:

```
public class MovementKey
{
    public float Time = 0;
    public float Duration;
    public Vector2 Traslation;            // Traslation is relative to previous key
    public TweeningFunction Function;

    internal float GetRatio( float Elapsed )
    {
        // Always return a value in [0..1] range
        //    0 .. Start position relative to accumulated traslations of previous keys
        //    1 .. Target relative position reached.. then should go to next key if avalaible
        return Function( Elapsed, 0, 1, Duration );
    }
}

```

And then you can handle the movement this way:

```
public class Movement {

    List<MovementKey> Keys;

    public void Update( float Seconds)
    {

        float ratio;
        if (Playing) Elapsed += Seconds;

        while ( index!= Keys.Count - 1 && Elapsed > Keys[iKey + 1].Time )
        {
            Traslation += Keys[iKey].Traslation;  // Relative
            index++;
        }

       if ( index == Keys.Count - 1 && Elapsed > Keys[iKey].Time + Keys[iKey].Duration )
       {
          ratio = 1;
          if ( DoLoop )
          {
              Elapsed -= (Keys[index].Time + Keys[iKey].Duration);
              Index = 0;
              Traslation = Vector2.zero;
          }
       }
       else {
           ratio = Keys[index].GetRatio( Elapsed - Keys[index].Time );
       }

       Position = DefaultPosition + Traslation + ratio * Keys[index].Traslation;
   }

```

"DefaultPosition" is the start position, "Traslation" accumulates movement of several keys, and each key traslation is relative to the previous key, so when you multiply it by a ratio factor \[0..1\] it returns the interpolated relative traslation walked to reach that key from the previous key...

Here you have another video that shows a platform movement defined as described here...

http://www.youtube.com/watch?v=ZPHjpB-ErnM&feature=player\_detailpage#t=104s

I have redone this code trying to make it easy to understand... maybe it has some bug... the original code handle several instance of the same movement but with some delays among each instance... I'm sure this code can be redesigned to be easier...
> 3 votes

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


# Question
Title: Slide 2d Vector to destination over a period of time
I am making a library of GUI controls for games I make with XNA. I am currently developing the library as I make a game so I can test the features and find errors/bugs and hopefully smash them right away.

My current issue is on a slide feature I want to implement for my base class that all controls inherit. My goal is to get the control to slide to a specified point over a specified amount of time. Here is the #region containing the code

```
#region Slide
    private bool sliding;
    private Vector2 endPoint;
    private float slideTimeLeft;
    private float speed;
    private bool wasEnabled;
    private Vector2 slideDirection;
    private float slideDistance;

    public void Slide(Vector2 startPoint, Vector2 endPoint, float slideTime) {
        this.location = startPoint;
        Slide(endPoint,slideTime);
    }

    public void Slide(Vector2 endPoint, float slideTime) {
        this.wasEnabled = this.enabled;
        this.enabled = false;
        this.sliding = true;
        Vector2 tempLength = endPoint - this.location;
        this.slideDistance = tempLength.Length(); //Was this.slideDistance = (float)Math.Sqrt(tempLength.LengthSquared());
        this.speed = slideTime / this.slideDistance;
        this.endPoint = endPoint;
        this.slideTimeLeft = slideTime;
    }

    private void UpdateSlide(GameTime gameTime) {
        if (this.sliding) {
            this.slideTimeLeft -= gameTime.ElapsedGameTime.Milliseconds;
            if (this.slideTimeLeft >= 0 ) {
                if ((this.endPoint-this.location).Length() != 0){//Was if (this.endPoint.LengthSquared() > 0 || this.location.LengthSquared() > 0) {
                    this.slideDirection = Vector2.Normalize(this.endPoint - this.location);
                }
                this.location += this.slideDirection * speed * gameTime.ElapsedGameTime.Milliseconds;//This is where I believe the issue is, but I'm not sure. It seems right to me... (Even though it doesn't work)
            }
            else {
                this.enabled = this.wasEnabled;
                this.location = this.endPoint;//After time, the controls position will get set to be the endpoint.
                this.sliding = false;
            }
        }
    }
    #endregion

```

this.location is the location of the control elsewhere defined in the class. I have looked at this blog as a huge reference and have googled around quite and have looked on many forums but can't find anything that shows how to implement it.

Please and Thanks for your time!

EDIT:

I have switched this line "this.location += this.slideDirection * speed * gameTime.ElapsedGameTime.Milliseconds;" several times to see what it does. My issue is getting the control to smoothly move to the end location. It moves after the time has expired, but It doesn't move other then that except flash in my face.

EDIT2:

I have used the first slide method with 3 parameters and it works except it doesn't do it in a period of time and once it gets to its destination, it starts moving randomly towards the previous location and the end location.

# Answer
Well, for stableness I advice you to integrate it. (instead of working with the velocity/speed of the widget `location +=` set its position `location =`)

Well, one of the ways to do it is using LERP (linear Interpolation)

For this, you have to first store the startPoint, the endPoint, the currentTime and the endTime(startTime we know is zero). So your code will be looking something like this: the LERP #region Slide private bool sliding; private Vector2 startPoint private Vector2 endPoint; private float currentSlideTime; private float endTime; private float speed; private bool wasEnabled;

```
public void Slide(Vector2 startPoint, Vector2 endPoint, float slideTime) {
    this.startPoint = startPoint;
    this.wasEnabled = this.enabled;
    this.enabled = false;
    this.sliding = true;
    this.endPoint = endPoint;
    this.endTime = slideTime;
}

public void Slide(Vector2 endPoint, float slideTime) {
    this.Slide(this.Location, endPoint, slideTime);
}

private void UpdateSlide(GameTime gameTime) {
    if (sliding) {
        currentTime += gameTime.ElapsedGameTime.Milliseconds;
        if (currentTime < endTime ) {
            float t = currentTime / endTime;
            location = Vector2.Lerp(startPoint, endPoint, t);
        }
        else {
            this.enabled = this.wasEnabled;
            this.location = this.endPoint;
            this.sliding = false;
        }
    }
}
#endregion

```

The key is here: `Vector2.Lerp(startPoint, endPoint, t);` It get a point between `startPoint` and `endPoint` with the percentage `t`. You could make it more smooth using `Vector2.Smoothstep(startPoint, endPoint, t);` It's pretty the same logic, but it smooths `t` value gradually, you just have to change this line.

And if you want even more control, you can use Vector2.Hermite or Vector2.Spline, but they are complicated and I'm pretty sure that if you don't understand them, you don't need them :P
> 0 votes

# Answer
Speed normally is distance per time. You divide time by distance.

Why `(float)Math.Sqrt(tempLength.LengthSquared());` Instead of just `tempLength.Length();`

Why do you check whether the "endPoint" or the "location" is at (0,0) before calculating the "slideDirection"? You probably want to check if `this.endPoint - this.location` has length 0.
> 0 votes

# Answer
You mention that you want this to smoothly slide from one location to another. Using a simplistic linear function, aka velocity/speed will not accomplish this. It will result in a jerky start/stop.

If you want to have a smooth slide transition you will need to implement a cubic curve or something similar. The `Microsoft.Xna.Framework.MathHelper` class provides an implementation of this curve through the `SmoothStep` method. All you will need to do is provide it your start and end values and a `float` between 0.0f and 1.0f representing the elapsed time of your animation. It will return the appropriate intermediate value.
> 0 votes

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


# Question
Title: Find out what word you are hovering mouse over
I want to be able to pop up something when the user hovers over particular words that are on a label in pygame.

Can anyone give me a good (or even bad) idea on how to implement this (doesn't have to be pygame specific)? Do I have to put each word in a different label and place them one after the other?

(what I'm calling a label is the result of font.render)

# Answer
When you use `Surface.blit()`, a rectangle is returned which you can associate with your label. You could consider keeping a list of these, or a list of tuples of the returned `Rect` and the text or label callback. In your main loop, you can iterate over this list and call `Rect.collidepoint(pygame.mouse.get_pos())` to find out if the mouse is in the current iteration step's `Rect`.
> 4 votes

---
Tags: pygame
---


# Question
Title: Costs/profit of/when starting an indie company
In short, I want to start a game company. I do not have much coding experience (just basic understanding and ability to write basic programs), any graphics design experience, any audio mixing experience, or whatever else technical. However, I do have a lot of ideas, great analytical skills and a very logical approach to life. I do not have any friends who are even remotely technical (or creative in regards to games for that matter).

So now that we've cleared that up, my question is this: how much, minimally, would it cost me to start such a company? I know that a game could be developed in under half a year, which means it would have to operate for half a year prior, and that's assuming that the people working on the first project do their jobs good, don't leave game breaking bugs, a bunch of minor bugs, etc.. So how much would it cost me, and what would be the likely profit in half a year? I'm looking at minimal costs here, as to do it, I would have to sell my current apartment and buy a new, smaller one, pay taxes, and likely move to US/CA/UK to be closer to technologically advanced people (and be able to speak the language of course).

EDIT: I'm looking at a small project for starters, not a huge AAA title.

# Answer
> 14 votes
This is mostly an unanswerable question, but I'll go through some of the things you mention.

You don't have any useful skills to bring to the table - sorry to be blunt - so you basically have to bankroll the enterprise if you want anybody to take you seriously.

Your main cost is the people you need to employ. Unless you know what sort of game you're going to make, you're not going to know how many people you need, so that hinders things somewhat. But I'll assume you can make the game you want to make with 1 programmer and 1 artist.

According to the Game Developer 2011 Game Industry Salary Survey you'd expect to pay a programmer about $7750 a month and artists about $6300. Most developers can be hired for significantly less than that - but with a small team, you probably can't afford to gamble on junior people. So that's almost $85,000 on salary for six months - not including paying yourself. Perhaps you can save a few thousand on less experienced developer, but there are other roles such as sound, music, web developer, etc, so I don't imagine you'll be able to do it much more cheaply than that.

You may be able to get away without spending money on an office and have people work from home instead, but you'll probably have to spend on technology and infrastructure - this could be anything from next to nothing to maybe $5000 for a few engine licenses, app approval fees and developer network fees, server hosting, IT support, etc.

Then you'll need some sort of publicity for the game. That means advertising campaigns, marketing, PR, etc. I would expect to spend several thousand on that if you mean business.

So, I would estimate the costs for you to be roughly in the area of $100,000.

How much profit would you make? Well, most games don't make a profit. One survey of iOS games said the average revenue was $165,121, so you might expect profit of $65,000. Unfortunately revenue is not distributed normally across all games - and in fact the median revenue was $2,400, meaning you might more commonly expect to lose about $97,000. So it's a very risky gamble.

I would suggest learning a technical skill so that you can contribute directly to your game and decrease your salary costs. It also means you can work on the game while otherwise employed, and then only take the company full time when the game is released and successful - if it ever reaches that point.

# Answer
> -1 votes
We are on the same boat. I'm from Philippines Manila I also wanted to start a game dev company. Right now we formed 3 to 4 investors each of us will contribute time, laptop, a game engine as of the moment. Each one of us also has proficiencies. Artist, programmers, management, and a fund manager. I am a fund manager I'm a former bank employee so I know how to invest big money so that we could earn monthly income.basically you don't need to spend too much or big money like what I said each one of us will contribute.

If you want to start get at least 3 persons or close friends that you can work with no need to spend huge money just invest what you have.

Right now we acquire a new laptop, a drawing tablet, and soon we get game engine, servers and web hosting just a cheap one.

I only knew basic coding since my team is studying game devt course.

---
Tags: career, publishing, business, hiring
---


# Question
Title: Lighting get darker when texture is aplied
Im using OpenGL ES 1.1 for iPhone.

I'm attempting to implement a skybox in my 3d world and started out by following one of Jeff Lamarches tutorials on creating textures. Heres the tutorial: iphonedevelopment.blogspot.com/2009/05/opengl-es-from-ground-up-part-6\_25.html

Ive successfully added the image to my 3d world but am not sure why the lighting on the other shapes has changed so much. I want the shapes to be the original color and have the image in the background.

Before: https://www.dropbox.com/s/ojmb8793vj514h0/Screen%20Shot%202012-10-01%20at%205.34.44%20PM.png

After: https://www.dropbox.com/s/8v6yvur8amgudia/Screen%20Shot%202012-10-01%20at%205.35.31%20PM.png

Heres the init OpenGL:

```
- (void)initOpenGLES1
{
    glShadeModel(GL_SMOOTH);

    // Enable lighting
    glEnable(GL_LIGHTING);

    // Turn the first light on
    glEnable(GL_LIGHT0);

    const GLfloat           lightAmbient[] =  {0.2, 0.2, 0.2, 1.0};
    const GLfloat           lightDiffuse[] =  {0.8, 0.8, 0.8, 1.0};
    const GLfloat           matAmbient[] =    {0.3, 0.3, 0.3, 0.5};
    const GLfloat           matDiffuse[] =    {1.0, 1.0, 1.0, 1.0};
    const GLfloat           matSpecular[] =   {1.0, 1.0, 1.0, 1.0};
    const GLfloat           lightPosition[] = {0.0, 0.0, 1.0, 0.0};
    const GLfloat           lightShininess =   100.0;

    //Configure OpenGL lighting
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, matAmbient);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, matDiffuse);
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, matSpecular);
    glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, lightShininess);

    glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, lightDiffuse);
    glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);

    // Define a cutoff angle
    glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 40.0);

    // Set the clear color
    glClearColor(0, 0, 0, 1.0f);

    // Projection Matrix config
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    CGSize layerSize = self.view.layer.frame.size;

    // Swapped height and width for landscape mode
    gluPerspective(45.0f, (GLfloat)layerSize.height / (GLfloat)layerSize.width, 0.1f, 750.0f);

    [self initSkyBox];

    // Modelview Matrix config
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // This next line is not really needed as it is the default for OpenGL ES
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_BLEND);

    // Enable depth testing
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glDepthMask(GL_TRUE);
}

```

Heres the drawSkybox that gets called in the drawFrame method:

```
-(void)drawSkyBox
{
    glDisable(GL_LIGHTING);
    glDisable(GL_DEPTH_TEST);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    static const SSVertex3D vertices[] = {
        {-1.0,  1.0, -0.0},
        { 1.0,  1.0, -0.0},
        {-1.0, -1.0, -0.0},
        { 1.0, -1.0, -0.0}
    };

    static const SSVertex3D normals[] = {
        {0.0, 0.0, 1.0},
        {0.0, 0.0, 1.0},
        {0.0, 0.0, 1.0},
        {0.0, 0.0, 1.0}
    };

    static const GLfloat texCoords[] = {
        0.0, 0.5,
        0.5, 0.5,
        0.0, 0.0,
        0.5, 0.0
    };

    glLoadIdentity();
    glTranslatef(0.0, 0.0, -3.0);

    glBindTexture(GL_TEXTURE_2D, texture[0]);
    glVertexPointer(3, GL_FLOAT, 0, vertices);
    glNormalPointer(GL_FLOAT, 0, normals);
    glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);

    glEnable(GL_LIGHTING);
    glEnable(GL_DEPTH_TEST);
}

```

Heres the init Skybox:

```
-(void)initSkyBox
{
    // Turn necessary features on
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glBlendFunc(GL_ONE, GL_SRC_COLOR);

    // Bind the number of textures we need, in this case one.
    glGenTextures(1, &texture[0]); // create a texture obj, give unique ID
    glBindTexture(GL_TEXTURE_2D, texture[0]); // load our new texture name into the current texture

    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

    NSString *path = [[NSBundle mainBundle] pathForResource:@"space" ofType:@"jpg"];
    NSData *texData = [[NSData alloc] initWithContentsOfFile:path];
    UIImage *image = [[UIImage alloc] initWithData:texData];

    GLuint width = CGImageGetWidth(image.CGImage);
    GLuint height = CGImageGetHeight(image.CGImage);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    void *imageData = malloc( height * width * 4 ); // times 4 because  will write one byte for rgb and alpha
    CGContextRef cgContext = CGBitmapContextCreate( imageData, width, height, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big );

    // Flip the Y-axis
    CGContextTranslateCTM (cgContext, 0, height);
    CGContextScaleCTM (cgContext, 1.0, -1.0);

    CGColorSpaceRelease( colorSpace );
    CGContextClearRect( cgContext, CGRectMake( 0, 0, width, height ) );
    CGContextDrawImage( cgContext, CGRectMake( 0, 0, width, height ), image.CGImage );

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);

    CGContextRelease(cgContext);

    free(imageData);
    [image release];
    [texData release];
}

```

Any help is greatly appreciated.

# Answer
> 1 votes
Figured it out, had to add glDisable(GL\_TEXTURE\_2D) in order for the colors to be correct.

---
Tags: iphone, opengl-es
---


# Question
Title: How to implement curved movement while tracking the appropriate angle?
I'm currently coding a 2D top-down car game which will be turn-based. And since it's turn-based, the cars won't be controlled directly (i.e. with a simple velocity vector that adjusts its angle when the player wants to turn), but instead it's movement path has to be planned beforehand, and then the car needs to follow the path when the turn ends (think Steambirds).

This question has some interesting information, but its focus is on homing-missile behaviour, which I kinda had figured out, but doesn't really apply to my case, I think, since I need to show a preview of the path when the player is planning his turn, then have the car follow that path. In that same question, there's an excellent answer by Andrew Russel which mentions Equations of Motion and Bézier's Curve. Some of his other suggestions of implementation are specific to XNA though, so they don't help much (I'm using Marmalade SDK).

If I assume Bézier's Curve as the solution of choice, I'm left with one specific problem: I'll have the car's position (the first endpoint) and the target/final position (the last endpoint), but what should I use as the control point (assuming a square/quadratic curve)?

And whether I use Bézier's Curve or another parametric equation, I'd still be left with another issue: the car can't just follow the curve, it must turn (i.e. adjust its angle) accordingly. So how can I figure out which way the car should be pointing to at any given point in the curve?

# Answer
My answer will cover the following topics:

* How to form a suitable Bezier curve for turning a character or a car smoothly.
* How to maintain the same speed across the curve.
* How to change the angle smoothly during motion.

This is suitable for any character in any 2d game with a top down view and with minor adjustments could be used for 3d games as well.

Some images for intuition:

Top down **overview**

**Waypoints**

Move the car in a linear path(straight line) from the bottom to the 'Start' point. Now use a Bezier to get the car to the 'End' point through the 'Control' point. Use another linear path moving straight from the 'End' to the last point on the left.

The resulting **path**

Intro:

Quadratic Bezier function:

```
q(t) = (1-t) * ((1-t) * start + t * control) + t * ((1-t) * continue + t * end) =
(1-t) * (1-t) * start + t * t * end + (1-t) * t * control + t * (1-t) * control =
(t^2 - 2t + 1) * start + t^2 * end + 2 * t * (1 - t) * control =

```

You know the starting point(when you begin to turn) and the end point(when you are done turning and continue normally).

Creating a suitable Bezier:

To calculate the control point, use the x-value of the point that is directly bellow or above the turning point and the y-value of the point directly to the left or right of the turning point.

If the roads do not form a straight angle, simple draw an imaginary line through both roads and use the intersection as the control point. You can take a smoother turn if you pull the start & end points away from the control point.

Finding out the correct angle:

Break the curve into 10 - 100 waypoints depending on the length of the turn, the car should always point towards the next waypoint.

To do this, pick a step size:

```
stepSize = 0.01;

```

We start in the begining of the curve.

```
lastPoint = 0;
lastPointPos = q(lastPoint);

```

We move towards the next waypoint on the curve.

```
nextPoint = lastPoint + stepSize;
nextPointPos = q(nextPoint);

```

And the angle is the one between these two points:

angle = Math.atan2(nextPointPos.y - lastPointPos.y, nextPointPos.x, lastPointPos.x);

this link explains what Math.atan2 means:

http://msdn.microsoft.com/en-us/library/system.math.atan2.aspx

How to maintain your desired speed through the curve:

```
//Calculate how much the car can move this frame
moveAmount = carSpeed * deltaTime;
//Calculate distance from next waypoint on the Bezier Curve
distance = sqrt((car.x - nextPointPos.x)^2 + (car.y - nextPointPos.y));
While(moveAmount > 0)
//If it is close enough, move the car there and subtract the distance from the amount you can move during this frame
if(distance < moveAmount)
{
    moveAmount -= distance;

    lastPoint = nextPoint;
    lastPointPos = q(lastPoint);

    nextPoint += stepSize;
    mextPointPos = q(nextPoint);
}
//Otherwise move as much as you can towards the destination
else
{
    car.x += moveAmount * Math.cos(angle);
    car.y += moveAmount * Math.sin(angle);
    moveAmount = 0;
}

```
> 5 votes

---
Tags: movement, curves, beziers
---


# Question
Title: Artifacts when using SamplerState.LinearClamp in SpriteBatch
I'm using XNA 4.0 and VS2010 Express for Windows Phone and Windows Phone SDK 7.1. This is a platform game and I have a map made up of 16x16 textures that is drawn dynamically, tile by tile. When using SpriteBatch to draw my map with LinearClamp, I get artifacts that looks like blurry thin lines. They become visible when the camera moves from one pixel to another and when the camera is still, the artifacts disappear. Here's a small sample of what I mean:

Here's how I draw with the spritebatch:

```
SBWorld.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone, null, camera.View);

```

When using SamplerState.PointClamp the game just plays horribly (IMHO), so I cannot use that. Why do these lines appear and how do I get rid of those?

# Answer
> 3 votes
The problem is that the linear interpolation (the `Linear` part) is interpolating between the edge pixels of a tile and edge pixels from the next tile over, when your tiles do not line up *perfectly* with screen pixels.

Using the `Clamp` texture addressing mode would solve this if you had one tile per texture, instead of a sprite-sheet - but that has its own disadvantages (namely: severely decreased performance).

So the only real solution is to **add appropriate padding around tiles in your sprite-sheet** so that, rather than the linear interpolation taking pixels from other tiles, it takes pixels from the padding.

The other alternative, as mentioned in comments, is to snap the camera to whole pixel positions (providing your tiles are positioned and scaled correctly so that their pixels line up perfectly with screen pixels).

Also from comments: one of the `Point` addressing modes would turn off interpolation entirely, avoiding this problem. However this will result in artefacts if you have tiles at fractional pixel positions - as you already know.

---
Tags: xna, textures, platformer, spritebatch
---


# Question
Title: How can I create a spritesheet animation with big images?
If I have a 200x200 pixel sprite, and I want to create an animation for it with 30 different frames, how can I accomplish that? I can't put them on one texture/spritesheet.

# Answer
You just need to abstract your animation system enough that it doesn't care (read: know) where each frame of the animation is coming from. I have built one such system myself where each animation sequence is built up using a list of frames, where each frame is merely a rectangular section of some image. Using that set of definitions, the animation sequence does not know that each frame is on a different texture.

Assuming you're restricted to something larger than 256x256, you can still pack multiple frames into each texture. I would recommend doing this for a number of reasons that I'll let someone else explain.
> 3 votes

# Answer
*This is an extension of @John McDonald's answer.*

Here's a stripped-down example of how to abstract your code-base so other systems of your library/application won't care about individual files. (Example is in C#):

```
public static class TextureStorage {
    public List<TextureObject> Textures;  // list of all textures used in the game
}

public class AbstractTexture {
    public int TextureId;         // the index of the texture
    public Rectangle SourceRect;  // the source rect describing where in the texture
                                  // to get the image from

    public TextureObject GetTextureObject() {
        return TextureStorage.Textures[ this.TextureId ];
    }
}

```

Now everything can reference your `AbstractTexture` and not care what file it came from.

When your rendering system goes to draw a frame, you'll have all the information handy:

```
public void Draw() {
    ...
    someBlitFunction(
        someObject.AbstractTexture.GetTexture(), // the texture to render
        someObject.AbstractTexture.SourceRect,   // the source rect
        someObject.Position,                     // the dest rect
        ... );
    ...
}

```
> 1 votes

# Answer
You can convert the size of your image a little bigger or smaller according to the appropriate size. I had used this link - http://www.garyshood.com/imageconvert/ You can use a size that would be completely divisible by 2. For example, if your image size is 200, then 200/2=100;100/2=50;50/2=25, so here 25 is not divisible by 2. Therefore, 200 is not an appropriate size. You can use 1024, 512, 256, 128 and so on..
> 1 votes

---
Tags: opengl, java, sprites, libgdx, spritesheet
---


title: Java 2D Tile Collision

text:
# Question
Title: Java 2D Tile Collision
I have been working on a way to do collision detection forever, and just can't figure it out. Here's my simple 2D array:

```
for (int x = 0; x < 16; x++) {
           for (int y = 0; y < 16; y++) {
              map[x][y] = AIR;
              if(map[x][y] == AIR) {
                 air.draw(x * tilesize, y * tilesize);

              }

           }
        }

    for (int x = 0; x < 16; x++) {
           for (int y = 6; y < 16; y++) {
              map[x][y] = GRASS;
              if(map[x][y] == GRASS) {
                 grass.draw(x * tilesize, y * tilesize);

              }

           }
        }
    for (int x = 0; x < 16; x++) {
           for (int y = 8; y < 16; y++) {
              map[x][y] = STONE;
              if(map[x][y] == STONE) {
                 stone.draw(x * tilesize, y * tilesize);
              }

           }
        }

```

I want to do it with rectangles, and using the intersect() method, but how would I go about adding rectangles to all the tiles?

Edit:

My player moves like this:

```
if(input.isKeyDown(Input.KEY_W))
    {
        shiftY -= delta * speed;
        idY = (int) shiftY;

        if(shift == true)
        {
            shiftY -= delta * runspeed;
        }

        if(isColliding == true)
        {
            shiftY += delta * speed;
        }
    }

    if(input.isKeyDown(Input.KEY_S))
    {
        shiftY += delta * speed;
        idY = (int) shiftY;

        if(shift == true)
        {
            shiftY += delta * runspeed;
        }

        if(isColliding == true)
        {
            shiftY -= delta * speed;
        }
    }

    if (input.isKeyDown(Input.KEY_A)) {
        steve = left;
        shiftX -= delta * speed;
        idX = (int) shiftX;

        if(shift == true)
        {
            shiftX -= delta * runspeed;
        }

        if(isColliding == true)
        {
            shiftX += delta * speed;
        }
    }

    if (input.isKeyDown(Input.KEY_D)) {
        steve = right;
        shiftX += delta * speed;
        idX = (int) shiftX;

        if(shift == true)
        {
            shiftX += delta * runspeed;
        }

        if(isColliding == true)
        {
            shiftX -= delta * speed;
        }
    }

```

(I have tried my own collision code, but its horrible. Doesn't work in the slightest)

# Answer
> 2 votes
First, in your example you do:

```
if(isColliding == true)

```

Where `isColliding` is calculated?

An easy way to check for collision in a tiled environment is to check the tile facing the player e.g if the player wants to move up and if he's currently on tile `x,y`, you will check if the tile `x,y-1` is a blocking tile (is not `AIR` in your case, i suppose).

The above method only works if the player have the size of the tiles and if the player move tile by tile, and it does not seem to be your case.

If your player has a totally different size than your tiles and/or can move more/less than `TILE_SIZE` per frame, you will need to use a bit more complex approach (also described here).

Basically, you need to create a new Shape for each of your game entities and keep them in a kind of Collection and each time your player move, proceed all the shapes in this collection and check if one of them intersect with your player's shape.

```
public Class CollisionSystem {

    public static List<Shape> collidingShapes = new...

    public static boolean checkPlayerCollision(Shape playerShape) {
        for (Shape s : collidingShapes) {
            if (s.intersects(playerShape) {
                 //or do some more precise collision calculation here, like pixel perfect
                 return true;
         }
         return false;
    }

```

It's a really simplified example since in a real case you will probably need to update position of the shapes for moving entities.

---
Tags: 2d, java, collision-detection, slick
---


# Question
Title: Understanding how to create/use textures for games when limited by power of two sizes
I have some questions about the creating graphics for a game.

As an example. I want to create a motorbike. (1pixel = 1centimeter) So my motorbike will have 200 width and 150 height. (200x150) But the libgdx only allows to load sizes with the power of 2?! (2,4,8,16,...)

First I thought about that way. I will create my bike with the size (200x150) and save it as png. Than I will open it again (e.g. with gimp) resize the image to a size which uses values with power of 2 (128x128). I will load that as texture in the programm and set width as 200 and height as 150.

But wouldn't it be a problem? Because I will lose some pixel information when I make the first conversation.?! Isn't it?

# Answer
The reason you're limited to power-of-two sizes is due to how video ram works. Note that what you should do is typically make the image the next highest power of two (.e. 512x256), and then just use a portion of that image for your graphics. You'd be setting your UV coordinates to only use a subsection of the image onto whatever triangles you're rendering.

If you're worried about memory usage, you could also use some of that left over space on different objects and UV map those objects to that part of the texture. Making a texture like this is also known as an "atlas".
> 11 votes

# Answer
You must use texture coordinates instead of resizing, like draw only part of the whole texture. I don't know how it works in libgdx but it's common to use this approach. Another approach is to use texture atlas, you have in memory e.g 1024x1024 and then when you load your image you load it to atlas rectangle.
> 3 votes

# Answer
You can convert the size of your image a little bigger or smaller according to the appropriate size. I had used this link - http://www.garyshood.com/imageconvert/ You can use a size that would be completely divisible by 2. For example, if your image size is 200, then 200/2=100;100/2=50;50/2=25, so here 25 is not divisible by 2. Therefore, 200 is not an appropriate size. You can use 1024, 512, 256, 128 and so on.. And then you can use portions of that image in your graphics. The other alternative would be to combine all your textures into the texture atlas easily using the libgdx Texture Packer GUI and then using texture from that atlas.
> 0 votes

---
Tags: opengl, graphics, libgdx, lwjgl
---


title: How to remove the FPS text on slick2d?

text:
# Question
Title: How to remove the FPS text on slick2d?
How do I remove the frame rate text on the upper left corner?

# Answer
`setShowFPS(false)` from GameContainer. Use google (great tool trust me) and RTFM. Do you make a bit of research before asking here, you could save a lot time by simply typing *slick2d hide fps* in google.

Please accept the answers you got.
> 6 votes

---
Tags: java, slick
---


# Question
Title: Texture not rendering in correct order in xna 4?
I am making a simple board game. In the game there is a fixed background called myTexture and others are textureGoat and textureTiger whicha are to be placed on top of the background(myTexture). But i am having problem that fourth and fifth component is not displaying however, the sixth component( i.e. myTexture) is appearing. Here is my code, please look at it

```
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Green);

        // TODO: Add your drawing code here
        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

        //placing tiger
        spriteBatch.Draw(textureTiger, new Rectangle(22, 25, 50, 50), Color.White);//first component
        spriteBatch.Draw(textureTiger, new Rectangle(22, 407, 50, 50), Color.White);//second component

        spriteBatch.Draw(textureTiger, new Rectangle(422, 25, 50, 50), Color.White);//third component
        spriteBatch.Draw(textureTiger, new Rectangle(422, 407, 50, 50), Color.White);//fourth component

        //placing goat
        spriteBatch.Draw(textureGoat, new Rectangle(125, 110, 50, 50), Color.White);//fifth component

        //placing background
        spriteBatch.Draw(myTexture, new Rectangle(0, 0, 500, 500), Color.White);//sixth component

        spriteBatch.End();
        base.Draw(gameTime);
    }

```

# Answer
> 0 votes
you are drawing background last, thus covering everything drawn before.

when you use immediate sorting (i.e. you don't explicitly specify the z-order), you need to draw **from bottom to top**, as if you were layering transparent paper, where each Draw call is a new layer. you draw **background first, then what is supposed to be on background second, etc...**, so if your comments mean that "first component" is supposed to be topmost, **you need to completely reverse the order of your draw calls**.

# Answer
> 2 votes
Since you are using BackToFront sort mode you might want to use this draw method;

SpriteBatch.Draw (Texture2D, Vector2, Nullable, Color, Single, Vector2, Vector2, SpriteEffects, Single)

where the last element is the "Sort Depth". This is the parameter that will be used by your sprite batch to choose the order in which to draw things. Since the draw method you are using doesn't set the "Sort Depth" value all sprites will be drawn in the same order you called draw in.

As an alternative, you can simply change the order in which you are calling Draw for each sprite, with objects at the back being drawn first so they don't get drawn over the top.

NOTE:

BackToFront is the sort order recommended for drawing sprites which have some transparency. If your textures have no transparent areas then you will want to use FrontToBack. Also, if you have some with no transparency and some with transparency, you might consider drawing the non-transparent ones first with a sort mode set to FrontToBack and then draw the transparent ones with the sort mode set to BackToFront. Unless performance becomes an issue, I would stick with BackToFront for all sprites and set the "Sort Depth". You can always change it later.

---
Tags: xna
---


title: Keeping rotation between two objects

text:
# Question
Title: Keeping rotation between two objects
In my XNA game I have two objects that collide. When the first object collides with the other it is able to latch on to it and move it about the world. I am having a problem with the math here (Math isn't my strong point). I currently have the second object latch on to the first and move around with it, but I cannot get it to keep it's original direction. So, if the object is facing up it should keep this direction relative to how it is being rotated with the original item.

Any tips on how I could best to achieve this?

# Answer
> 3 votes
As far as angle is concerned, just keep the angle of the second object the same as the angle of the first. For position, when the two objects collide with each other, find the distance of the second object from the first using the distance formula.

```
distance = math.sqrt((x2 - x1)^2 + (y2 - y1)^2)

```

To find the position of the second object relative to the first object:

```
x2 = x1 + distance * math.cos(angle)
y2 = y1 + distance * math.sin(angle)

```

# Answer
> 2 votes
In addition to @tesselode's answer, I would recommend you keep a list of attached objects for every world object in your game. Something along the lines of `List<WorldObject> AttachedObjects`. Then, when you'd detect a collision, you would add the black rectangle to the red one's `AttachedObjects`. After that, it's only a matter of updating the children's positions using @tesselode's method every time you update the parent's position.

# Answer
> 2 votes
I'm assuming one of the two will have control over the other one, much like a fork-lift. In your drawing, I'm assuming this is the black one, and the red one is the package. You only mention you're having trouble with angles, so that's all I'll cover.

When the objects latch together, you should remember the angle difference between the two (I'll call this Theta). I have drawn this in figure 2 with the arrows from the first figure drawn over each other. Until the objects are unlatched, the angle of the Red object will be determined by the Black's angle plus Theta, as shown in figure 3.

```
// When Latching:
theta = Red.angle - Black.angle;

// When retrieving Red's angle:
Red.angle = Black.angle + theta

```

# Answer
> 1 votes
You could implement an ability to have child objects for an object (where child objects would be automatically affected by changes to the position/rotation of parent). Then upon collision when they should latch together, you make an invisible object and make both of the attached objects its children. Then, instead of applying transformations (movement, rotation) on the individual objects, you apply it on the big one, OR you could still apply forces to the individual children objects, which would check "do I have a parent?", and if yes, the force would be sent to the parent (which would merge forces from all child objects into one vector it would apply to itself).

Also, this approach should properly handle their rotation, if you calculate center of mass for the invisible parent according to weights of the latched objects, which John's method doesn't seem to accomplish (joined object rotate around their new shared center of mass, not around center of mass of one of the objects), and you could easily nest this kind of behavior without any additional code required. It seems to be the more robust and flexible approach.

+condition if the force applied to child is strong enough to break the joint, and you can handle the "unlatching" of it by simply removing the parent-\>child relationship. If there's only one child left, you make it seperate too and remove also the invisible parent.

I can provide more details (with pictures and at least pseudocode and such) if you're interested.

---
Tags: xna, rotation
---


title: Character coding / programming

text:
# Question
Title: Character coding / programming
Lately I tryed a few times to create characters for some games, but at some certain point (especially when collision detection came in) everything became messy and the interaction between chars, the world and certain items had a lot of bugs. So here is my question, how do you ussualy keep track of actions that your character is allowed to do, or more in general do you have some links / advices how to set up a char efficiantly?

I´m working on a char right now, who should at least be able to run, jump, pick items up and use different fighting animations. Most ideas I came up with until now use some kind of action.priority / action.duration system to determain whats possible and what not, or a "action-manager" which defines for every action what is possible from that action on but it all doesnt work that well together.

# Answer
> 2 votes
You should look at FSMs -

Here's a good description for novice programmers: http://blog.manuvra.com/modeling-a-simple-ai-behavior-using-a-finite-state-machine/

# Answer
> 0 votes
As my comment suggested: Look at how statemachines work.

---
Tags: game-design, character
---


# Question
Title: How do I randomly generate a top-down 2D level with separate sections and is infinite?
I've read many other questions/answers about random level generation but most of them deal with either randomly/proceduraly generating 2D levels viewed from the side or 3D levels. What I'm trying to achieve is sort of like you were looking straight down on a Minecraft map. There is no height, but the borders of each "biome" or "section" of the map are random and varied. I already have basic code that can generate a perfectly square level with the same tileset (randomly picking segments from the tileset image), but I've encountered a major issue for wanting the level to be infinite: Beyond a certain point, the tiles' positions become negative on one or both of the axis. The code I use to only draw tiles the player can see relies on taking the tiles position and converting it to the index number that represents it in the array. As you well know, arrays cannot have a negative index. Here is some of my code:

This generates the square (or rectangle) of tiles:

```
    //Scale is in tiles
    public void Generate(int sX, int sY)
    {
        scaleX = sX;
        scaleY = sY;

        for (int y = 0; y <= scaleY; y++)
        {
            tiles.Add(new List<Tile>());

            for (int x = 0; x <= scaleX; x++)
            {
                tiles[tiles.Count - 1].Add(tileset.randomTile(x * tileset.TileSize, y * tileset.TileSize));
            }
        }
    }

```

Before I changed the code after realizing an array index couldn't be negative my for loops looked something like this to center the map around (0, 0):

```
for (int y = -scaleY / 2; y <= scaleY / 2; y++)
for (int x = -scaleX / 2; x <= scaleX / 2; x++)

```

Here is the code that draws the tiles:

```
            int startX = (int)Math.Floor((player.Position.X - (graphics.Viewport.Width) - tileset.TileSize) / tileset.TileSize);
        int endX = (int)Math.Ceiling((player.Position.X + (graphics.Viewport.Width) + tileset.TileSize) / tileset.TileSize);
        int startY = (int)Math.Floor((player.Position.Y - (graphics.Viewport.Height) - tileset.TileSize) / tileset.TileSize);
        int endY = (int)Math.Ceiling((player.Position.Y + (graphics.Viewport.Height) + tileset.TileSize) / tileset.TileSize);

        for (int y = startY; y < endY; y++)
        {
            for (int x = startX; x < endX; x++)
            {
                if (x >= 0 && y >= 0 && x <= scaleX && y <= scaleY)
                    tiles[y][x].Draw(spriteBatch);
            }
        }

```

So to summarize what I'm asking: First, how do I randomly generate a top-down 2D map with different sections (not chunks per se, but areas with different tile sets) and second, how do I get past this negative array index issue?

# Answer
> 2 votes
Both of your questions are answered separately on this site already.

For example, this question: Random map generation, can easily be applied to your situation. Simply ignore the height (or don't display it but use it in biome generation). As well as this one: How can I create a random "world" in a tile engine?

Secondly, the issue with negative arrays can easily be solved. Don't use arrays. There are plenty of basic data structures that would work. Linked lists for example. Check out this question: A way to store potentially infinite 2D map data?

# Answer
> 0 votes
You'll probably also want to look at http://pcg.wikidot.com/category-pcg-algorithms Doesn't seem to be updated anymore, but contains a good amount of information about various procedural generation techniques for various purposes.

---
Tags: xna, 2d, procedural-generation, random
---


# Question
Title: A way to store potentially infinite 2D map data?
I have a 2D platformer that currently can handle chunks with 100 by 100 tiles, with the chunk coordinates are stored as longs, so this is the only limit of maps (maxlong\*maxlong). All entity positions etc etc are chunk relevant and so there is no limit there.

The problem I'm having is how to store and access these chunks without having thousands of files. Any ideas for a preferably quick & low HD cost archive format that doesn't need to open everything at once?

# Answer
> 17 votes
Create a custom map format for your game. It's easier than you might think. Just use the BinaryWriter class. First write the header in a few ints or uints. Information to include in the header:

* The magic string / magic number of you file format.
* The start/end/size of the chunks described in this file

and also (and here comes the performance critical part

* ints that describe the starting position inside the file. So you don't have to search for specific chunks.

With the above methode you can (and should) create an index of your files contents, containing some sort of description(a user specified name for the region/chunk, or just the coordinates) and as a second value the position in the file.

Then, when you want to load a specific chunk, you'll just have to search inside the index. When you got the position just set fileStream.Position = PositionOfChunkFromIndex and you can load it.

It's all about the design of the fileformat with the header describing the contents of the file most efficiently.

Just save the files with a custom extension you made up and there you go.

BONUS: Add BZip2 compression to specific regions of the file / the whole contents (not the header!!), so you can unpack specific chunks from the file, for a very small memory footprint.

# Answer
> 13 votes
I ran into a similar problem and decided to create my own structure to handle the data. It's based loosely on a quadtree, but has infinite (at least as big as an Int) expandability in all directions. It was designed to handle grid-based data which expanded from a central point, much like Minecraft does now. It is space efficient in memory, and very fast.

You can specify a minimum magnitude for each node (a magnitude of 7 would be 128x128) and once any node has a specified percentage of its subnodes populated, it automatically flattens itself into a two-dimensional array. This means that a very densely populated portion (e.g., a completely explored continent) will have the performance of an array (very fast) but a sparsely populated portion (e.g., a shoreline someone wandered up and down but didn't explore inland) will have good performance and a low memory usage.

My code can be found here. The code is complete, tested (unit- and load-tests), and quite optimized. The inner workings aren't too well documented yet, however, but all the public methods are so it should be usable. If anyone decides to try it out, feel free to contact me with questions or comments.

I've not yet used it to store data to a file, but it's an interesting problem and I may tackle that next.

# Answer
> 3 votes
You could use a database instead -- PostgreSQL has some special indexing capabilities optimized for this type of data which is located by X and Y coordinates. You can also specify that the data returned is within a certain radius rather than in a square or oblong shaped area.

PostgreSQL (free and open source)
http://www.postgresql.org/

There are other databases as well, and for the client-side you may find certain types to be better-suited to this since they can run stand-alone (initiated by your game client application) or can be included as part of a code library that you can "just use." The advantage is that you don't have to design an indexing scheme because most SQL database engines already do this quite well.

An advantage with the database approach is that you can make your chunks smaller (or get rid of chunks completely and just use tiles directly, but the use of at least small chunks/groups of many tiles may be more efficient depending on your design), and then use the SQL query to bring in a larger area than is viewable. By pre-loading to overlap nearby non-viewable areas, the tiles can be prepared *before* the player moves their character, resulting in a better (hopefully smoother) gaming experience.

I've noticed that some games keep a "cache" of the map data on the local hard drive after obtaining it the first time (this is undoubtedly to reduce network I/O), such as Ashen Empires:

Ashen Empires (free to play, beautiful 2D implementation)
http://www.ashenempires.com/

Keeping track of "last updated" timestamps with each chunk/tile will also be helpful since, for where locally stored data is available, the SQL query could include an additional "WHERE timestamp\_column \> $local\_timestamp" clause so that only updated chunks/tiles get downloaded (two benefits of saving bandwidth like this are lower connectivity costs, and less lag for your players, which will become more obvious when your game gets popular).

A screen shot from Ashen Empires (a few characters are at a local bank, and by the looks of those bones on the floor it looks like a few skeleton monsters must've wandered in and were likely slaughtered by the local town's guards):

# Answer
> 2 votes
Do not store and access them, store only the necessary random seeds as well as the player's changes to the map. Then generate required portions at run-time (run your generation algorithm, then apply the player's changes). With correct and consistent generation procedure, the resulting map will always be the same for the same starting seed.

Theoretically you can do literally infinite map that will save to a very small file this way.

# Answer
> 1 votes
Is there any way you can partition chunks (some kind of 'subcontinents / countries' in you world) ? So maybe you can have some kind of index files that let you quickly find which sub-file / part of bigger file you need to load to have a chunk in memory ...

# Answer
> 0 votes
You could take the idea from Minecraft. Originally they had a file per chunk. Now they use the MCRegion format, which groups chunks into 32x32 areas and stores one of those per file.

---
Tags: xna, 2d, c#, maps, platformer
---


# Question
Title: Custom shadow mapping in Unity 3D Free Edition
Since real time hard and soft shadows are Unity 3D Pro only features I thought I will learn Cg programming and create my own shadow mapping shader. But after some digging I found that the shadow mapping technique uses `depth textures`, and in Unity depth values can be accessed through a `Render Texture` object, which is Unity Pro only again. So is it true, that I cannot create real time shadow shaders as a workaround to the limitations of the free version?

# Answer
If nothing else, you can manually calculate shadows using techniques similar to low-resolution ray tracing, then somehow put them on screen. I think this would be fairly easy, since unity supports hit detection with custom rays and all scene objects that have a collider, but of course this is highly inefficient.

If you can't afford unity pro (not even the student version), I suggest looking at other 3d or game engines that satisfy your needs better.
> 6 votes

---
Tags: unity, shaders, shadow-mapping, cg
---


# Question
Title: Get intersection of vector in the middle of the screen
My screen resolution is 640x480 and I have two Vector2 objects located at (10,10) and (600, 320).

How can I connect these two objects and extend the line to encompass the whole screens width, how can I get the Y for the intersection at the center of the width (320)?

# Answer
> 2 votes
you have to use the equation of a line. I prefer to use parametric representation P(t)= 1-t\*(v1) + t\*V2 ; then you solve the equation where P1 = P2 ...

here is the detailed solution http://paulbourke.net/geometry/lineline2d/ you can also google "line line intersection"

# Answer
> 1 votes
Do you mean midpoint?

You can always set the two vectors equal to each other with a scalar multiple for each and solve, but this situation is not clear. Are we to assume they are pointing at each other?

---

Updated for clarity

You are asking for the point of intersection between two lines, one that is vertical - splitting the screen - at x=320, and one that is at some other non parallel point. With two lines, the point of intersection is the point where they are equal to each other.

I used the example of a vertical line (x=320) and a second line (y=13x+2) and all you have to do is set them equal to each other and solve. Since one line is x=320, so no matter what you do the x value needs to be 320. When you plug that value into the second equation, you get y=13(320)+2

This will give you the y position for the system of equations. You can find the line by using the vectors slope, or rise/run (change in y/change in x), and solve for the offset (y=mx+b, because your lines origin gives you the x and y positions.

Ex.

```
Two points (300,30), (450, 330);
The slope is (330-30)/(450-300)=(300/150)=2;
The y intercept is y=mx+b -> (30)=(2)(300)+b -> b=-570;
The line is thus y=(2)x-570;
This line intersects the x=320 line at:
y=(2)x-570 == x=320 -> y=(2)(320)-570 = 70
the point of intersection is: (320, 70)

```

http://www.analyzemath.com/Calculators\_2/intersection\_lines.html

# Answer
> 0 votes
If I understand correctly, there is a line from (10,10) to (600,320). Let's call these (x1,y1) and (x2,y2). The line needs to be extended to x=0 and x=640, and divided at x=320. This implies finding y for these 3 values of x.

You need to know the equation which describes the line. For a straight line, this will be in the form of:

```
y = slope*x + intercept

```

i.e. for all points on the line, this formula will be true.

Slope is just:

```
(change in y) / (change in x)

```

So:

```
y = ((y2-y1) / (x2-x1) * x) + intercept

```

Rearrange:

```
intercept = y - ((y2-y1) / (x2-x1) * x)

```

Substitute in x and y from either one of your known points. (x1,y1) used here:

```
intercept = y1 - ((y2-y1) / (x2-x1) * x1)

```

Subsitute the expressions you now have for slope and intercept back into the line equation:

```
y = slope*x + intercept

```

And you can then find y for any value of x.

---
Tags: xna, mathematics, vector
---


# Question
Title: pointers to member functions in an event dispatcher
For the past few days I've been trying to come up with a robust event handling system for the game (using a component based entity system, C++, OpenGL) I've been toying with.

```
class EventDispatcher {
  typedef void (*CallbackFunction)(Event* event);

  typedef std::unordered_map<TypeInfo, std::list<CallbackFunction>, hash_TypeInfo > TypeCallbacksMap;

  EventQueue* global_queue_;

  TypeCallbacksMap callbacks_;

  ...
}

```

**global\_queue\_** is a pointer to a wrapper **EventQueue** of **std::queue\<Event\*\>** where **Event** is a pure virtual class. For every type of event I want to handle, I create a new derived class of **Event**, e.g. **SetPositionEvent**.

**TypeInfo** is a wrapper on **type\_info**.

When I initialize my data, I bind functions to events in an unordered\_map using **TypeInfo(typeid(Event))** as the key that corresponds to a **std::list** of function pointers. When an event is dispatched, I iterate over the list calling the functions on that event. Those functions then **static\_cast** the event pointer to the actual event type, so the event dispatcher needs to know very little.

The actual functions that are being bound are functions for my component managers. For instance, **SetPositionEvent** would be handled by

```
void PositionManager::HandleSetPositionEvent(Event* event) {
   SetPositionEvent* s_p_event = static_cast<SetPositionEvent*>(event);
   ...
}

```

The problem I'm running into is that to store a pointer to this function, it has to be static (or so everything leads me to believe.) In a perfect world, I want to store pointers member functions of a component manager that is defined in a script or whatever. It looks like I can store the instance of the component manager as well, but the typedef for this function is no longer simple and I can't find an example of how to do it.

Is there a way to store a pointer to a member function of a class (along with a class instance, or, I guess a pointer to a class instance)?

Is there an easier way to address this problem?

# Answer
Yes you can store member function pointers, and here's a program demonstrating the syntax for that.

```
#include <iostream>

using namespace std;

struct X
{
    void f(int i) { cout << "X::f " << i << endl; }
};

int main()
{
    void (X::*pf)(int) = &X::f;

    X x;
    X *px = &x;

    (x.*pf)(4);
    (px->*pf)(5);
}

```

But it comes with many caveats. For example, you'll notice that the pointer embeds the class type, which means all callback targets would have to derive from the same base class. And that's just the beginning of the list.

The truth is, however, that your callback source really shouldn't care who it's calling, as long as it's been told to call back. For this purpose, you really should read up on Boost.Bind and Boost.Function (if you're using C++11, that would be std::bind and std::function).
> 3 votes

# Answer
With C++11, it's built in to the standard library, or if that's not an option, boost::bind might be what you are looking for.

I don't bother and use a free function that takes a void pointer for user data for my callbacks.
> 3 votes

---
Tags: c++, opengl, events
---


# Question
Title: What is a good starting project to get up to speed with vectors and vector math?
I have been getting into games programming recently. However, all I have made so far (in order) is Snake, Breakout and Tetris.

I want to take on a bigger project, and some research has led me to research vectors. I'd like to know what a good starting point would be to get up to speed with vectors and their associated math.

# Answer
> 2 votes
I guess that anything that has free (rather than tile-based) movement is a good start - in fact you could deal with Breakout's ball using vectors. I would definitely start with 2d rather than 3d.

I'm in a similar position and have written something like Asteroids as a first project. Problems that can be handled with vectors include:

* player vehicle's free 2d movement
* player vehicle's rotation (and thus acceleration and firing) independent from direction of travel
* player's bullets affected by the firing vehicle's movement
* movement of asteroid fragments after a sucessful bullet hit

I have also written AI for the player vehicle; the aiming part of this must take target movement (leading) and own movement into account, which again are good vector problems.

# Answer
> 2 votes
Most physic games uses vectors. Try to start with one that you like:

Ball Colisions:

* Snooker
* Golf
* Marbles

Free moves:

* Race
* Asteroids
* side-scroller

Math Curves:

* Angry birds style
* GunBound style
* Trow something as far as possible

These are just some ideas.

# Answer
> 1 votes
You are obviously interested in rendering related math. This and a lot more has been well packaged into Mathematics for Programming Computer Graphics.

# Answer
> 0 votes
This seems to be some nice article about vector maths : http://www.wildbunny.co.uk/blog/vector-maths-a-primer-for-games-programmers/

Vectors really aren't a big deal even if you're bad at math :)

They can be used in plenty of games, I suggest you choose something involving a bit of physics.

---
Tags: vector
---


# Question
Title: Which isometric angles can be mirrored (and otherwise transformed) for optimization?
I am working on a basic isometric game, and am struggling to find the correct mirrors.

Mirror can be any form of transform.

I have managed to get SE out of SW, by scaling the sprite on X axis by -1. Same applies for NE angle.

Something is bugging me, that I should be able to also mirror N to S, but I cannot manage to pull this one off.

Am I just too sleepy and trying to do the impossible, or a basic -1 scale on Y axis is not enough?

What are the common used mirror table for optimizing 8 angle (N, NE, E, SE, S, SW, W, NW) isometric sprites?

# Answer
> 4 votes
With standard player sprites you really only have 3 mirrors. NW/NE, W/E, and SW/SE. You can't mirror north and south because you're looking at the "back" of the avatar in one direction and the "front" in another. This means you need 5 directions authored and you can extrapolate 8 total.

This is assuming that the sprites are mirrorable, of course. Namely, that they're symmetrical along the vertical axis. Or that you don't care about the mirroring artifacts.

# Answer
> 6 votes
I will dare say that you should not do this. I have two main reasons for this.

1) Most objects cannot be mirrored. A person cannot. Maybe if the person is just standing. But if the person is holding something in its hand, if you mirror it, it will seems that he has changed hands, which in many cases is not what you want.

2) Isometric projection is meant to be pseudo 3D. This usually means that nicely drawn sprites will have some shadows, accents etc. To maintain the appearance, all sprites need to seem like they are lit from the same direction. If you start mirroring, then the shadows will switch sides as well, and it will all look out of whack.

I suppose there are situations where above points are not of concern, but most modern hardware can very easily handle thousands of sprites, and rendering each many thousands of times, so you are probably better off concentrating on general performance and not mirroring optimization.

---
Tags: sprites, rendering, isometric, optimization
---


title: Rotate to a set degree then stop Unity

text:
# Question
Title: Rotate to a set degree then stop Unity
I'm trying to make an object rotate up on the Y axis 90 degrees, then stop. I've got the rotating up bit working fine, it's getting it to stop once it hits 90.

Some of the things I've tried include the following:

```
float i = rotateSpeed * Time.deltaTime;
while ( x != 90 )
        {
        transform.Rotate( i, 0, 0);
        }

        int x = 0;
x++;

        if( x == 90 )
        {
            transform.Rotate( 0, 0, 0 );
        }

```

For some reason I can't get this simple thing to work. What am I missing / not doing?

# Answer
You may want to study your basic control flow structures and learn about scope. Also, using a `float` to rotate and an `int` to count the number of times you rotated would only work if your `i` was exactly `1`, which is very unlikely.

Depending on where this code is and how you want things to be displayed, you probably don't even want a `while` loop. A while loop would just run through all your rotation in one go, without updating whatever you're rotating on screen in-between. Basically having:

```
float totalRotation = 0;
float rotationAmt = rotateSpeed * Time.deltaTime;
while(totalRotation < 90)
{
    transform.Rotate(rotationAmt, 0, 0);
    totalRotation += rotationAmt;
}

```

is the same (though less accurate) as :

```
transform.Rotate(90, 0, 0);

```

Likely what you really want, to have your object be updated on screen while it rotates is to store the objects current rotation somewhere and also store it's *target rotation*:

```
//stored in the object you're rotating
float rotation = 0;
float targetRotation = 0;

...

//inside our update for the object check the rotation to see if we're where we want to be
float rotationAmt = rotateSpeed * Time.deltaTime;
if(rotation!= targetRotation)
{
    //first we check to see if there's just a small amount of rotation to shave off
    // this check keeps us from never reaching the target rotation
    if(abs(rotation-targetRotation) < rotationAmt) {
        transform.Rotate(rotation-targetRotation, 0, 0);
        rotation += rotation-targetRotation;
    } else {
        transform.Rotate(rotationAmt, 0, 0);
        rotation += rotationAmt;
    }
}

```

Now I know what you're going to do. You're going to copy and paste this code, and tell me it doesn't work. Don't do that. Just look at the code and see how it works. Then implement it yourself to fit your project. There are improvements that can be made to this code as well. Like checking which way to rotate to be fastest. Check this class to see how you might do that.
> 7 votes

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


# Question
Title: Naming conventions for external resources?
While we develop games, then we have utilize several external resources, for example

* Image
* Sound
* Animation
* Sprite Sheet

Is there any good naming convention regarding these external resources?

# Answer
I have a folder for my sources, i call it `src` and a folder for assets called `assets` which looks like:

```
- Assets
    - Images
    - Sounds
    - Scripts
    - Animations
    - Config (for property files etc.)
    - ... (maybe others regarding the game i'm working on)

```

**EDIT:** And regarding naming conventions for those resources

* Use a period to separate the base file name from the extension in the name of a directory or file.
* No white space
* Do not end a file or directory name with a space or a period.
* For long file name use hyphen(-)
* Any other character that the target file system does not allow.
> 8 votes

# Answer
You can take help from Microsoft's File,Stream,Path and Namespace resources

Also following resource
> 3 votes

# Answer
I am a fan of object-oriented folder structures.

```
- Gui
   - HealthBar.png
   - ManaBar.png
   - Layout.xml
- Creatures
  - Elves
    - Elf Sharpshooter
      - Definition.txt
      - Sprite.png
      - Script.as
    - Elf Fighter
      - Definition.txt
      - Sprite.png
      - Script.as

```

Make sure that the paths are case-sensitive else you will run into problems with everything not windows.
> 1 votes

---
Tags: assets
---


title: Entity System and rendering

text:
# Question
Title: Entity System and rendering
Okey, what I know so far; The entity contains a component(data-storage) which holds information like; \- Texture/sprite \- Shader \- etc

And then I have a renderer system which draws all this. But what I don't understand is how the renderer should be designed. Should I have one component for each "visual type". One component without shader, one with shader, etc?

Just need some input on whats the "correct way" to do this. Tips and pitfalls to watch out for.

# Answer
This is a difficult question to answer because everyone has their own idea about how an entity component system should be structured. The best I can do is share with you some of the things I have found to be most useful for me.

## Entity

I take the fat-class approach to ECS, probably because I find extreme methods of programming to be highly inefficient (in terms of human productivity). To that end, an entity to me is an abstract class to be inherited by more specialized classes. The entity has a number of virtual properties and a simple flag that tells me whether or not this entity should exist. So relative to your question about a render system, this is what the `Entity` looks like:

```
public abstract class Entity {
    public bool IsAlive = true;
    public virtual SpatialComponent   Spatial   { get; set; }
    public virtual ImageComponent     Image     { get; set; }
    public virtual AnimationComponent Animation { get; set; }
    public virtual InputComponent     Input     { get; set; }
}

```

## Components

Components are "stupid" in that they don't *do* or *know* anything. They have no references to other components, and they typically have no functions (I work in C#, so I use properties to handle getters/setters - if they do have functions, they are based around retrieving data that they hold).

## Systems

Systems are less "stupid", but are still dumb automatons. They have no context of the overall system, have no references to other systems and hold no data except for a few buffers that they may need to do their individual processing. Depending on the system, it may have a specialized `Update`, or `Draw` method, or in some cases, both.

## Interfaces

Interfaces are a key structure in my system. They are used to define what a `System` can process, and what an `Entity` is capable of. The Interfaces that are relevant for rendering are: `IRenderable` and `IAnimatable`.

The interfaces simply tell the system which components are available. For example, the rendering system needs to know the bounding box of the entity and the image to draw. In my case, that would be the `SpatialComponent` and the `ImageComponent`. So it looks like this:

```
public interface IRenderable {
    SpatialComponent Component { get; }
    ImageComponent   Image     { get; }
}

```

## The RenderingSystem

So how does the rendering system draw an entity? It's actually quite simple, so I'll just show you the stripped down class to give you an idea:

```
public class RenderSystem {
    private SpriteBatch batch;
    public RenderSystem(SpriteBatch batch) {
        this.batch = batch;
    }
    public void Draw(List<IRenderable> list) {
        foreach(IRenderable obj in list) {
            this.batch.draw(
                obj.Image.Texture,
                obj.Spatial.Position,
                obj.Image.Source,
                Color.White);
        }
    }
}

```

Looking at the class, the render system doesn't even know what an `Entity` is. All it knows about is `IRenderable` and it is simply given a list of them to draw.

## How It All Works

It may help to also understand how I create new game objects and how I feed them to the systems.

**Creating Entities**

All game objects inherit from Entity, and any applicable interfaces that describe what that game object can do. Just about everything that is animated on screen looks like this:

```
public class MyAnimatedWidget : Entity, IRenderable, IAnimatable {}

```

**Feeding the Systems**

I keep a list of all entities that exist in the game world in a single list called `List<Entity> gameObjects`. Each frame, I then sift through that list and copy object references to more lists based on interface type, such as `List<IRenderable> renderableObjects`, and `List<IAnimatable> animatableObjects`. This way, if different systems need to process the same entity, they can. Then I simply hand those lists to each one of the systems `Update` or `Draw` methods and let the systems do their work.

**Animation**

You might be curious how the animation system works. In my case you may want to see the IAnimatable interface:

```
public interface IAnimatable {
    public AnimationComponent Animation { get; }
    public ImageComponent Image         { get; set; }
}

```

The key thing to notice here is the `ImageComponent` aspect of the `IAnimatable` interface is not read-only; it has a *setter*.

As you may have guessed, the animation component just holds data about the animation; a list of frames (which are image components), the current frame, the number of frames per second to be drawn, the elapsed time since the last frame increment, and other options.

The animation system takes advantage of the rendering system and image component relationship. It simply changes the image component of the entity as it increments the animation's frame. That way, the animation is rendered indirectly by the rendering system.
> 8 votes

# Answer
See this answer to see the kind of system I'm talking about.

The component should contain the details for what to draw and how to draw it. The rendering system will take those details and draw the entity in the way specified by the component. Only if you were to use significantly different drawing technologies would you have separate components for separate styles.
> 5 votes

# Answer
The key reason to separate logic into components is to create a set of data that when combined in an entity they produce useful, reusable behavior. For example separating a Entity into a PhysicsComponent and RenderComponent makes sense as it's likely that not all entities will have Physics and some entities might not have Sprite.

In order to answer your question you need to look at your architecture and ask yourself two questions:

1. Does it make sense to have a Shader without a Texture
2. Will separating Shader from Texture allow me to avoid code duplication?

When splitting a component it's important to ask this question, if the answer to 1. is yes then you probably have a good candidate for creating two separate components, one with a Shader and one with Texture. The answer to 2. is usually yes for components like Position where multiple components can use position.

For example, both Physics and Audio might use the same position, rather then both components storing duplicate positions you refactor them into one PositionComponent and require that entities that use PhysicsComponent/AudioComponent also have a PositionComponent.

Based on the information you've given us it doesn't seem like your RenderComponent is a good candidate for splitting into a TextureComponent and ShaderComponent as shader's are wholly dependent on Texture's and nothing else.

Assuming you're using something similar to T-Machine: Entity Systems a sample implementation of a RenderComponent & RenderSystem in C++ would look something like this:

```
struct RenderComponent {
    Texture* textureData;
    Shader* shaderData;
};

class RenderSystem {
    public:
        RenderSystem(EntityManager& manager) :
            m_manager(manager) {
            // Initialize Window, rendering context, etc...
        }

        void update() {
            // Get all the entities with RenderComponent
            std::vector<RenderComponent>& components = m_manager.getComponents<RenderComponent>();

            for(auto component = components.begin(); entity != components.end(); ++components) {
                // Do something with the texture
                doSomethingWithTexture(component->textureData);

                // Do something with the shader if it's not null
                if(component->shaderData != nullptr) {
                    doSomethingWithShader(component->shaderData);
                }
            }
        }
    private:
        EntityManager& m_manager;
}

```
> 3 votes

# Answer
Pitfall #1: overdesigned code. Think about whether you really need every thing you implement because you're going to have to live with it for quite some time.

Pitfall #2: too many objects. I wouldn't use a system with too many objects (one for each type, subtype and whatever) because it just makes automated processing harder. In my opinion, it's much nicer to have each object control a certain feature set (as opposed to one feature). For example, making components for each bit of data included in rendering (texture component, shader component) is too divided - you'd usually need to have all those components together anyway, wouldn't you agree?

Pitfall #3: too strict external control. Prefer changing names to shader/texture objects because objects can change with renderer/texture type/shader format/whatever. Names are simple identifiers - it's up to the renderer to decide what to make out of those. One day you might want to have materials instead of plain shaders (add shaders, textures and blend modes from data, for example). With a text-based interface, it's much easier to implement that.

As for the renderer, it can be a simple interface that creates/destroys/maintains/renders objects created by components. The most primitive representation of it could be something like this:

```
class Renderer {
    function Draw() { ... }
    function AddSprite( ... ) { ... return sprite; }
    function RemoveSprite( sprite ) { ... }
    ...
};

```

This would allow you to manage these objects from your components and keep them far enough to allow you render them any way you want.
> 2 votes

---
Tags: architecture, rendering, entity-system
---


# Question
Title: Flash: Memory usage is low but framerate keeps dropping
So I'm working on a puzzle game in flash. For all intents and purposes it's like Tetris. I spawn blocks, they move around the screen, then they get destroyed and disappear. I was having some trouble with the memory usage being too high over time so I read up on memory management and I think I have that figured out now. It's definitely climbing slower than it was before, but the framerate is still taking a huge dive after playing for a while. If it's not a memory leak what else could be causing this? Thanks in advance.

# Answer
> 4 votes
Either 2 of these it think:
\- It would very well be that you are deleting stuff from the display-list but still have references in other places( like arrays ) that are still being processed. This keeps building up and completely hogs your game. ( but Flash can easily handle tons of objects )

or

-Your algorithm, even though simplistic, is flawed and is doing more work than necessary. Memory leaks are nearly impossible in AS3 unless you loose an object that holds a reference to an object you can't reach anymore ( like Events that aren't destroyed and never have their weak flag set to true).

This combined with the above one can really tear down the performance.

# Answer
> 2 votes
http://gamedev.michaeljameswilliams.com/2009/03/25/avoider-game-tutorial-12/ you should visit this part of that tutorial, it will probably contain your problem, which is for example, not unloading the childs you create and instead just freeze them out of view. I could try to tell you details but check that out, at least you should get a lot of really useful tips.

---
Tags: flash, actionscript-3
---


# Question
Title: First Minecraft mod not working: make a new sword
I am making my first mod and cannot see what is wrong with it. I am using MCP and Modloader. For my first mod I was going to make swords.

I started with making a new `EnumToolMaterials`

```
WOOD(0, 59, 2.0F, 0, 15),
STONE(1, 131, 4.0F, 1, 5),
IRON(2, 250, 6.0F, 2, 14),
LAPIS(3, 750, 7.0F, 2, 14),
OBSIDIAN(3, 1000, 7.5F, 3, 12),
EMERALD(3, 1561, 8.0F, 3, 10),//diamond
GREEN(3, 2000, 9.0F, 4, 10),//emerald
GOLD(0, 200, 12.0F, 0, 22);

```

then here is the mod class

```
public class _Mod_Yamiko extends BaseMod{

    /* mod itemts */
    public static final Item swordLapis = (new ItemSword(600, EnumToolMaterial.LAPIS)).setItemName("swordLapis");
    public static final Item swordObsidian = (new ItemSword(601, EnumToolMaterial.OBSIDIAN)).setItemName("swordObsidian");
    public static final Item swordGreen = (new ItemSword(602, EnumToolMaterial.GREEN)).setItemName("swordGreen");

    public void load(){
        //set images
        swordLapis.iconIndex = ModLoader.addOverride("/gui/items.png","/gui/swordLapis.png");

        ModLoader.addName(swordLapis, "Lapis Sword");
        //craft
        ModLoader.addRecipe(new ItemStack(_Mod_Yamiko.swordLapis, 1), new Object[]{
            " X ", " X ", " Y ",
            'X', Block.dirt,
            'Y', Item.stick
        });
    }

    public String getVersion(){
        return "0.1";
    }
}

```

Then I made a 16×16 .png image. I am not sure where to save it so I recompiled and reobfuscated, took the mod files and put it in my local Minecraft install, added the image where it be should be. No problems when playing but I cannot make the new sword.

# Answer
It should be

```
ModLoader.addRecipe(new ItemStack(_Mod_Yamiko.swordLapis, 1), new Object[]{
            " X ", " X ", " Y ",
            Character.valueOf("X"), Block.dirt,
            Character.valueOf("Y"), Item.stick
        });

```

when referencing the characters
> 3 votes

---
Tags: java, minecraft-modding, modding
---


title: MarteEngine Tile Collision

text:
# Question
Title: MarteEngine Tile Collision
I need to add collision to my tile map using MarteEngine. MarteEngine is built of of slick2D. Here's my tile generation code: Code:

```
public void render(GameContainer gc, StateBasedGame game, Graphics g) throws SlickException
   {
      for (int x = 0; x < 16; x++) {
         for (int y = 0; y < 16; y++) {
            map[x][y] = AIR;
               air.draw(x * GameWorld.tilesize, y * GameWorld.tilesize);
         }
      }

   for (int x = 0; x < 16; x++) {
         for (int y = 7; y < 8; y++) {
               map[x][y] = GRASS;
               grass.draw(x * tilesize, y * tilesize);
         }
      }

   for (int x = 0; x < 16; x++) {
         for (int y = 8; y < 10; y++) {
            map[x][y] = DIRT;
               dirt.draw(x * tilesize, y * tilesize);
         }
      }

   for (int x = 0; x < 16; x++) {
         for (int y = 10; y < 16; y++) {
            map[x][y] = STONE;
               stone.draw(x * tilesize, y * tilesize);
         }
      }
      super.render(gc, game, g);

   }

```

And one of my tile classes (they're all the same, the image names are just different): Code:

```
package MarteEngine;

import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

import it.randomtower.engine.entity.Entity;

public class Grass extends Entity {

   public static Image grass = null;

   public Grass(float x, float y) throws SlickException {
      super(x, y);

       grass = new Image("res/grass.png");

       setHitBox(0, 0, 50, 50);

       addType(SOLID);
   }

}

```

I tried to do it like this: Code:

```
for (int x = 0; x < 16; x++) {
         for (int y = 7; y < 8; y++) {
               map[x][y] = GRASS;
               Grass.grass.draw(x * tilesize, y * tilesize);
         }
      }

```

But it gave me a NullPointerException. No idea why, everything looks initialized right? I would be very grateful for some help!

# Answer
> 0 votes
From the code you posted it looks like you never actually *call* the constructor for `Grass`, so `Grass.grass` is still `null`. It never gets a `new Image(...)` assigned to it. If you try to call a method on a `null` object, you'll get a `NullPointerException`.

What are the values of `AIR`, `GRASS`, `DIRT`, and `STONE`? Are they global?

**EDIT:**

Where in your code do you call the constructor for `Grass` (or `Air`, `Stone`, or `Dirt`)?

```
Grass theGrass = new Grass(0, 0);

```

---
Tags: java, slick
---