title: SDL_BlitSurface does not works

text:
# Question
Title: SDL_BlitSurface does not works
I have an issue with the SDL\_BlitSurface... When I blit (SDL\_BlitSurface) in a transparent (background) surface, it does not blits, actually I tried all the existants functions (SDL\_DisplayFormat(Alpha), SDL\_SetAlpha, SDL\_FilLRect/SDL\_ColorKey, per-pixel method) anything! The r/g/b/a mask are good. Here is the code:

```
SDL_Surface * surfed_texture =
SDL_CreateRGBSurface(SDL_SWSURFACE,surface_width,surface_height,32,
0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
Uint32 tormv = SDL_MapRGB(surfed_texture->format,255,0,255);
int possiblecolors[] = { 255,0,255,255,255,255 };
int in_pc = 0;
if(color.r == possiblecolors[0] && color.g == possiblecolors[1] && color.b == possiblecolors[2]){
in_pc=3;
}
SDL_FillRect(surfed_texture,NULL,SDL_MapRGB(surfed_texture
>format,possiblecolors[in_pc],possiblecolors[in_pc+1],possiblecolors[in_pc+2]));
SDL_SetColorKey(surfed_texture, SDL_SRCCOLORKEY, SDL_MapRGB(surfed_texture
>format,possiblecolors[in_pc],possiblecolors[in_pc+1],possiblecolors[in_pc+2]));
SDL_Surface * temporal = NULL;
for(int i=0;i<(int)buff_split.size();i++){
const char* c_text = buff_split.at(i).c_str();

temporal = TTF_RenderText_Blended(font,c_text,color);

int w_fo;
int h_fo;
TTF_SizeText(font,c_text,&w_fo,&h_fo);

SDL_Rect rct;
rct.y=i*lineSkip;

if(txt_align==ALIGN_LEFT){
    rct.x=0;
}else if(txt_align==ALIGN_CENTER){
    rct.x = surface_width/2 - w_fo/2;
}else if(txt_align==ALIGN_RIGHT){
    rct.x = surface_width - w_fo;
}

rct.w=0;
rct.h=0;

// Blit surface

SDL_BlitSurface(temporal,NULL,surfed_texture,&rct);

SDL_FreeSurface(temporal);
}

```

# Answer
> 1 votes
Have you tried rendering on a software surface. In my experience SDL2.0 only works with SDL\_RENDERER\_SOFTWARE not with SDL\_RENDERER\_ACCELERATED ( flags supplied to SDL\_CreateRenderer).

Gijs

---
Tags: c++, opengl, sdl
---


# Question
Title: Can a rules engine produce manageable and complex AI?
I am currently in the middle of creating an AI village simulation in Java. Having implemented a simple rules engine for dialog, I am wondering if this DSL can be extended for AI. I have previously implemented both GOAP and behavior trees, but considered GOAP to be confusing for the average user. Behavior trees may still be an option.

In this case, I expect the AI to be able to control interactions between villagers (covered within the rules system already) and to manage the goals/daily actions of both individual villagers and the village as a whole. Actions could range from gathering resources, to deciding what to build on a broader scale.

However, I have concerns about whether a rules system will be able to manage hierarchy or many complex situations. There may also be some interaction with non technical users, so understandability is important.

The rules engine as it stands currently takes in a number of facts on an event, matches it to the best rule and executes a number of actions.

The outcome of the AI needs to be sufficiently complex as to be believable; for example, there may be many competing desires to relax, work on a pressing task etc. This needs to be able to be managed and prioritized as tasks come up. A village wide AI can assign tasks to individual villagers based on their abilities and the urgency of the task. There are randomized events that can change the priority of certain tasks. My main concern is whether the rules engine will be performant, be able to schedule tasks well and be responsive to dynamic conditions.

Is a rules based engine desirable for this kind of AI?

# Answer
Yes, a rules engine can be used for complex AI, at least to some extent. Unfortunately, game AI rules engines are apparently rather rare. Most of my Google searches on the subject turned up results unrelated to games or just questions regarding using it in games (including this question). I only found a few games described as using rules engines.

One of them was a real time strategy game called HomeWorld 2. Another real time strategy game that uses a rules engine to a minimal extent is AI War: Fleet Command. The AI for that game is described in greater detail in this series of blog posts by the game's creator.

As for whether a rules based engine would be suitable to your game, I suggest you try to implement a relatively simple rules based engine and test it with your game. If it seems like it would work for your game, then you can expand it. Otherwise, you can discard it and try a different approach.
> 1 votes

---
Tags: ai, behavior
---


title: Following a path in a smooth fashion

text:
# Question
Title: Following a path in a smooth fashion
I am currently making a 2d tower defense game with a static, predetermined lane that the enemies follow (i.e. towers cannot block the path and path finding is *not* the problem I am trying to solve).

I am trying to figure how exactly to make units follow this lane in a **smooth** way. I have two rough ideas about how to do this, but I would love some input on which is likely to be easier to implement/the more standard technique. Or of course if I there is some totally different way that I haven't considered I would love to learn about that as well.

**Waypoints:** My first idea was to define the path as a series of hard coded waypoints. Units would then use a basic "seek" steering algorithm (such as this one) to move to each waypoint along the path in succession. However, I have wondered if it might be hard to keep the units from deviating to much from the lane I want them to follow. I wonder if inability to turn sharply enough might cause them to sort of "glide" out off of the desired lane. I suppose I might be able to prevent that though by allowing for a relatively strong steering force to be applied?

**Bezier Curves:** The second solution I have considered is to define the path with a bezier curve and at each time step calculate the point along the curve with is (dt * speed) away from the unit's current location. I suspect that this technique would make it much easier to precisely define the path that units will follow, but I don't know know how exactly to go about implementing this. Any suggestions?

Also, I don't this will change anyone's answers, but units also must be able to travel at a constant speed along the path. Additionally, I am programming this game in python using the pyglet framework.

If anything about the question is unclear please let me know.

Edit: Also for whatever its worth, I'm sort of trying to replicate the movement behavior of enemies in the Kingdom Rush.

# Answer
Allow me to introduce you to Craig Reynolds' famous paper on Steering Behaviors For Autonomous Characters. If you haven't read it, you should, it'll help you think through these sorts of problems, in particular take a look at the section on pathfinding.

The idea of Reynolds' paper is that you can use simple forces that combine to produce life-like, improvisational navigation around the environment. The movements are not based on path planning or global calculations, but instead use local information, such as neighbors’ forces, which makes them simple to understand and implement, but still produces very complex movement patterns.

The beauty of the approach is that you can combine several of the behaviors together. So, for example, your characters may have both a path-finding behavior as well as a separation behavior (to keep them from clumping too much), which can be combined as a weighted sum.

Another benefit to using steering behaviors is that there are a number of existing open source implementations in a variety of languages (e.g., opensteer).

---

UPDATE: I took a look at Kingdom Rush, and I think I may have misunderstood what you meant by "smoothly." I took it to mean more lifelike, but I think what you're after is more like the characters are on a train track. Also, reading more carefully, I see that one of your requirements is that "units must be able to travel at a constant speed along the path." Steering behaviors is not going to give you a constant speed of movement, but simple pathfinding combined with waypoints will. (I.e., don't use the "seek" behavior to get to the waypoint, instead simply determine the direction vector and have the unit move at full speed to that waypoint.) Use more waypoints to smooth out the route.
> 8 votes

# Answer
The solution in this Gamasutra article may be what you're looking for. The basic idea is to cast rays to a waypoint that is two steps ahead of your current waypoint "stepping" the ray a fraction of a cell's length and at each "stepping" of the ray checking to see if your player's collision volume collides with anything at the stepped position of the ray. If the ray gets all the way to the waypoint that's two steps ahead, then you can get rid of the intermediary waypoint. you can then continue this same process all the way to the "goal" waypoint...thus if your path can be accomplished by a straight line to the goal a straight line to the goal is the route your character will take. here's the article: http://www.gamasutra.com/view/feature/131505/toward\_more\_realistic\_pathfinding.php?print=1

It also contains great things about turn radius and more natural turning behaviors and such...
> 2 votes

---
Tags: animation, sprites, ai, movement
---


title: 3D game demo in XNA

text:
# Question
Title: 3D game demo in XNA
Does anyone know of a decent 3D game tutorial with source code?

I'm really new with 3D development for XNA and have found that the best way to figure out how to code for something is to look at pre-existing source code and figure out what goes where.

# Answer
Here are all the official XNA samples: http://xbox.create.msdn.com/en-US/education/catalog/
> 1 votes

# Answer
xna is dead and no longer supported. i suggest getting started with unity, friendlier for a starter and a more complete solution than xna.
> -2 votes

---
Tags: xna, 3d, xna-4.0
---


title: Checking bounds of a quad

text:
# Question
Title: Checking bounds of a quad
I want to know how would I tell if a quad touches another quad in my game built in Slick2D. I have a class that I named "Bounds" which has 4 "Point" objects which just store an X and a Y value and a "Bounds" object stores 4 "Point"s. Simply it has 4 2D vectors, one stores the top left, another stores the top right, another stores the bottom right and the other stores the bottom left. I need to be able to check if two quads based of those 4 coordinates are inside each other. Does anyone have an idea of what I should do?

# Answer
> 3 votes
I cant tell if you just want to do bounding box collision or somthing more complicated with the vectors but if you just want to see if a rectangle is inside another rectangle then check if :

```
box1.left   < box2.right &&
box1.right  > box2.left &&
box1.top    < box2.bottom && // if your Y starts at bottom of screen and gets higher
box1.bottom > box2.top       // as you go up the screen swap these round. aka the > <

```

If all that is true you have a collision, You can then check what side of a box is actully hiting by just changing some of that code around.

Like if the left side of one box is more left then the right side and more right the left side of another box then you know the left side of you box is inside another and not your right side.

Hope that helps, if not sorry :S

Edit: now with pic to help work out that code :\]

# Answer
> 0 votes
I actually wouldn't assume that the boxes are axis aligned since they are defined using vector2's for each corner. In fact no where does it say that these are rectangles. My solution would be to do a point test on each point from 1 quad in the other and then do the same from the other perspective... using a winding algorithm you can test if a point is inside or outside of another polygon(quad). If 1 or more points is inside then they are colliding.

Here is a link to a discussion about algorithms that determine if a point is inside a polygon(quad)

http://geomalgorithms.com/a03-\_inclusion.html

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


title: Movement on a curved planet surface

text:
# Question
Title: Movement on a curved planet surface
I'm looking for a solution for moving a variety of objects over the uneven surface of my planet. The idea is that I will have a number of objects that follow the planetary landscape moving about in random directions.

The planet surface is made up of 6 sphere projected planes, all have been displacement mapped to create a "bumpy" surface. A grid based movement system would be ideal as it lends itself to a lot of pathfinding solutions. I am also using Unity, so leveraging the Physics engine is an option, but past experience hasn't yielded very good results.

I'm having trouble understanding the best approach for realistic movement, would it be a matter of calculating gravity and then translating the object along its forward, right etc. Or on the other hand would It be more a case of pre-calculating the path from A to B and applying that movement.

I've looked all over for some ideas on this subject but have found nothing. A few suggestions would be greatly appreciated.

Thanks.

# Answer
> 1 votes
Having used Unity before, I would try my best to leverage the physics engine as best as I could. Basically what I would do is represent the positions in polar coordinates + a rotation for facing direction. So essentially the polar coordinates would give you a unique position on a perfect sphere(which you could map to a grid keeping in mind that the grid wraps around and pinches off at certain places) and the extra rotation would specify the angle around the vector perpendicular to the sphere at that location. Unity and the physics engine will take care of the actual motion as long as you provide a constant gravitation "pull" from the centroid of the object towards the centroid of the planetoid. To create motion around the planetoid you simply need to provide a force perpendicular to the normal vector of the planet surface at that position rotated to the direction of travel around the sphere.

# Answer
> 2 votes
You can treat the surface as a 2D heightmap of your planet.

This greatly simplifies the calculations needed; for gravity, simply apply a force downwards, and your main movement is on one plane. When you're done, you can simply convert the coordinates to the spherical coordinate system through some trig functions.

---
Tags: movement, terrain, planet
---


title: Collision with Two Angled Platforms

text:
# Question
Title: Collision with Two Angled Platforms
I've encountered a problem in my attempt to implement Collision Handling for a game I'm creating, involving a collision with two angled platforms.

I'm using GJK-EPA for detecting/handling collisions so I can pull the penetration vector and depth from each collision, and using this I have been calculating the angle of the surface the player collides with.

What I don't understand, is how I should resolve a collision when the character is moving from one slope to a steeper slope, one slope to a shallower slope and flat-surface -\> slope and vice versa.

I attempted comparing penetration depths but due to the nature of GJK, I can only do this with some additional vector maths which then refuses to work for steep-\>shallow slopes. Additionally: It sometimes seems to 'spasm' on direct contact with vertices.

Basically, can anyone tell me a good/common way of handling angles of objects that are touching TWO platforms, using GJK-EPA?

Thank you!

(To note: I'm relatively new to game development, and I'm trying to get some smooth slope physics working, just so you know the 'situation').

# Answer
> -1 votes
not too sure either, but I could imagine using the angle of incidence (movement vector), mirroring it along the normal of the slope/surface and applying the resulting vector to your movement. this way a steeper slope would affect much compared to a shallow slope. your movement vector is a mix between gravity and applied forces such as user input accerlerating your object over time.

I don't know GJK-EPA nor do I understand what you mean with penetration depths. Do I understand you at least correctly?

---
Tags: 2d, collision-detection, platformer
---


title: Better quality texture when zooming

text:
# Question
Title: Better quality texture when zooming
Is there any way to have better quality textures ?

I thought that creating huge textures will improve their quality in game, that's why I draw textures with 0.25f or 0.5f scale.

I understand that computer can't display 4 pixels in 1 screen pixel, but how people do to have beautiful sprites while zooming ? even on smartphones...

Hope you can help me.

# Answer
I believe what you're looking for is Mipmapping.
> 3 votes

# Answer
equally they could be using vector art work that scales infinitly without pixelating

another method that high end game engines use is detail maps - its an extra texture that is overlaid onto the asset/wall/model when the player is very close to said asset

see a better explanation here - http://wiki.polycount.net/DetailMap
> 2 votes

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


# Question
Title: Ligdx Box2d : convert box2d coordinates into screen coordinates
I'm new in libgdx and i have a little problem. I created a body in box2d and i want to assign it a sprite; for that i need to get the position of the body,then insert into the main loop the updated position of the sprite, right ? So..i made so but the sprite doesn't align right on the body, but in a corner. What should I write in body.setPosition() and in sprite's position ?

P.S: sorry but i can't post a screenshot :(

# Answer
You have to consider different scenario for box2d and scene. Both the thing have different anchor point. Box2d assign position based on the centre of the object while scene assign position based on the corner of the object.

Either you can change the anchor point of the object to centre to match it with box2d or you have to calculate position of the sprite or object.

If you want position of the object to (100,100) in scene coordinate then same assignment for box2d object would be (100/PTM\_RATIO,100/PTM\_RATIO) where PTM\_RATIO value is 32.0f.

Now using above calculation both sprite and object get same position. Also consider position and size of the object must be divided by PTM\_RATIO in box2d otherwise it show abnormal behaviour.
> 1 votes

---
Tags: libgdx, sprites, box2d
---


# Question
Title: Create Box2D and engine polygon Box2D body without sprite
I have created my body using following code: (please read full description)

```
    Body polyBody;
    final BodyDef mBodyDef = new BodyDef();
    mBodyDef.type = BodyDef.BodyType.DynamicBody;
    mBodyDef.position.x = 20;
    mBodyDef.position.y = 5;
    polyBody= mPhysicsWorld.createBody(mBodyDef);
    final PolygonShape mPoly = new PolygonShape();
    mPoly.set(vertices);
    objectFixtureDef.shape = mPoly;
    polyBody.createFixture(objectFixtureDef);
    mPoly.dispose();

```

Now it's time for connecting my polygon with body using `PhysicsConnector` and when I do `mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(mPoly, polyBody, true, true));` it doesn't accept `mPoly` as I expect an `IAreaShape` instead.

Is there any way that I can change it into an `IAreaShape`? Or can anyone suggest how can I create a body without using sprite? It's strictly prohibited that I can't use sprite as I need to cut/slice my body further.

# Answer
> 0 votes
I think you are working with AndEngine. You misunderstood the concept of PhysicsConnector. PhysicsConnector need sprite and body to create. But here mPoly is a PolygonShape object that has functionality of box2d not of sprite.

If you don't want to use sprite then there is no need of PhysicsConnector. Basically PhysicsConnector used to attach sprite with body. So developer does not need to render it manually.

Also you have to use pixel to meter ratio to apply position and size of the object. In AndeEngine you can use constant with PhysicsConstant.PIXEL\_TO\_METER\_RATIO.

---
Tags: android, box2d, andengine
---


# Question
Title: How can I replicate the color limitations of the NES with an HLSL pixel shader?
So since 256 color mode is depreciated and no longer supported under Direct3D mode, I got the idea to use a pixel shader instead to simulate the NES palette of all possible colors so that fading objects and whatnot don't have smooth fade outs with alpha channels. (I know objects couldn't really fade out on the NES, but I have all objects that do fade in and out on a solid black background, which would be possible with palette swapping. Also, the screen fades in and out when you pause which I know also was possible with palette swapping as it was done in a few Mega Man games.) Problem is, I know next to nothing about HLSL shaders.

How do I do it?

# Answer
In the pixel shader you could pass in a 256x256 Texture2D with the pallet colors all lined up horizontally in a row. Then your NES textures would be converted to direct3D Texture2Ds with ever pixel converted to a 0-255 index value. There is a texture format that only uses the red value in D3D9. So the texture would only take up 8bits per pixel, but the data that comes into the shader would be from 0-1.

// Pixel shader might look like this:

```
float4 mainPS() : COLOR0
{
    float4 colorIndex = tex2D(MainTexture, uv);
    float4 palletColor = tex2D(PalletTexture, float2(colorIndex.x, 0);
    return palletColor;
}

```

**EDIT: A more correct way would be to add in all the blending pallet version you need aligned vertically in the texture and referencing them with your colorIndex's 'alpha' value:**

```
float4 mainPS() : COLOR0
{
    float4 colorIndex = tex2D(MainTexture, uv);
    float4 palletColor = tex2D(PalletTexture, float2(colorIndex.x, colorIndex.a);
    return palletColor;
}

```

**A third way would be to just fake the NES low fade quality by toon shading the alpha color:**

```
float4 mainPS() : COLOR0
{
    float4 colorIndex = tex2D(MainTexture, uv);
    float4 palletColor = tex2D(PalletTexture, float2(colorIndex.x, 0);
    palletColor.a = floor(palletColor.a * fadeQuality) / fadeQuality;
    //NOTE: If fadeQuality where to equal say '3' there would be only 3 levels of fade.
    return palletColor;
}

```
> 4 votes

# Answer
If you don't really care about texture memory usage (and the idea of blowing an insane amount of texture memory to achieve a retro look has a kind of perverse appeal) you could build a 256x256x256 3d texture mapping all RGB combinations to your selected palette. Then in your shader it just becomes one line of code at the end:

```
return tex3d (paletteMap, color.rgb);

```

It may not even be necessary to go all the way to 256x256x256 - something like 64x64x64 may be sufficient - and you could even change palette mappings on the fly using this method (but at significant cost owing to a large dynamic texture update).
> 3 votes

# Answer
*(both of my solution works only if you dont care about changing palletes on the fly using shaders)*

You can use any type of texture and do just a simple computation on a shader. Trick is that you have more color information than you need, so what you will just get rid of information that you dont want to.

8bit color is in formar **RRRGGGBB**. Which gives you 8 shades of red and green and 4 shades of blue.

This solution will work for any RGB(A) color format textures.

```
float4 mainPS() : COLOR0
{
    const float oneOver7 = 1.0 / 8.0;
    const float oneOver3 = 1.0 / 3.0;

    float4 color = tex2D(YourTexture, uvCoord);
    float R = floor(color.r * 7.99) * oneOver7;
    float G = floor(color.g * 7.99) * oneOver7;
    float B = floor(color.b * 3.99) * oneOver3;

    return float4(R, G, B, 1);
}

```

*note: i wrote that from the top of my head, but im really sure it will compile and work for you*

---

**Another possibility**, would be to use **D3DFMT\_R3G3B2** texture format that is actually same as 8bit graphics. When you put data to this texture, you can use simple bit operation per byte.

```
tex[index] = (R & 8) << 5 + ((G & 8) << 2) + (B & 4);

```
> 1 votes

---
Tags: shaders, pixel
---


title: Limit sprite to windows bounds?

text:
# Question
Title: Limit sprite to windows bounds?
I'm making a game in XNA and I want to limit the movement of a sprite to the screen boundaries. How would I do this?

https://i.stack.imgur.com/ZqH0M.jpg

# Answer
The simplest way, if you just want the sprite to not go off the screen is this

```
if (spritePosition.X > Window.ClientBounds.Width - spriteTexture.Width)
     spritePosition.X = Widow.ClientBounds.Width - spriteTexture.Width;
if (spritePosition.Y > Window.ClientBounds.Height - spriteTexture.Height)
     spritePosition.Y = Widow.ClientBounds.Height - spriteTexture.Height;

if (spritePosition.X < 0)
    spritePosition.X = 0;
if (spritePosition.Y < 0)
    spritePosition.Y = 0;

```
> 2 votes

---
Tags: xna
---


# Question
Title: What causes polygonal twitching in older games?
I'd like this answer large part to curiosity and I'd like to recreate it with our modern computers somehow.

By old games I'm referring to ps1 games. My specific example would be Megaman Legends I've not really noticed it in any other games maybe Final Fantasy 8. There probably are others.

When your looking around, vertices "lock" into different locations very twitchily. The Textures follow too. Sometimes vertices supposedly connecting to each other are in two different locations looking like one is jutting out of place.

Heres a video of the game. You have to look at about mid range to see changes is location.

https://www.youtube.com/watch?feature=player\_detailpage&v=ojGrAcZw3pA#t=961s

Its probably not something uncommon to old polygonal graphics.

My only theory is its rounding floating points to the closest integer but that doesn't seem plausible to me.

\[edit\] PSX doesn't have floating points there goes my theory XD.

I'd like to hear anyone's theory even if they don't know. Take a stab. I'll investigate any of them myself.

# Answer
> 4 votes
Floating or fixed point precision would have caused this problem. Older games commonly used fixed point as it was traditionally faster than floating point, prior to widespread FPU support in consumer machines which began in the early 1990's. (The Intel 386SX / DX gap showed the floating point performance difference clearly in a game like Doom which relied heavily on fractional numbers.)

Consider a range of numbers which uses only 1 decimal place. If every full unit were to represent a metre, then every decimal place would represent a tenth of a meter (AKA a decimeter). Since this is your maximum precision, objects will obviously jump in increments of 0.1m, rounding up or down to the nearest decimeter as necessary.

Fixed point is how we tend to traditionally think of decimal point numbers: numbers that can be represented down to some smallest fraction of a single unit (as in the above decimeters example). *However*, given that every number must be stored in a certain number of bits (for modern IEE-754 floating point, a commonly-used standard, this is 32 bits or 4 bytes), we have a limit on precision for what sits to the left of the point, i.e. the significand, and what to the right of it, i.e. the fraction.

Now, given n total bits in which to store such a number, we have two choices.

* We can choose to use x of n bits to store the upper part, and the remaining y of n bits to store the lower part, in a fixed point format (eg. 16.16 fixed point, a total of 32 bits used). This is conceptually simple, but not space-efficient.
* Floating point offers another option, and this is why it is named "floating": The bits can be used in a variable configuration to provide a much larger range, at the expense of whatever is on the other side of our "floating" decimal point. Range for the fraction comes at the expense of the significand; and vice versa. Given this, one can see how smooth movement over galactic (or greater) distances is possible in simulations (googling single-precision floating point range" will indicate just how large a range 32-bit IEEE-754 can support, never mind higher-precision standards which use 64- or 128-bit words.)

This should give you some indication as to why in this age, where even low-spec mobile devices now support floating point arithmetic, we no longer have the aliasing effects you describe.

As for the vertex issue, I find it likely that this is due to the fact that before GPU tech became widespread in the days of 3DFX, it may have been common to duplicate vertices, possibly because getting a good winding order along with linear (and thus efficient) data access is not a particularly trivial problem and it may be easier for performance reasons to simply duplicate most vertices so that each triangle consists of 3 unique vertices... this would positively impact cache performance at the very least. In that case, vertices might be matched in any of a number of ways, from manual entry to precalculated positions for different orientations to runtime calculation. But I am going to hazard a guess that this sort of thing is unique for every game. I remember games which simply didn't do this at all. So it is likely this was a specific quirk of individual engines that occurred for different reasons.

# Answer
> 3 votes
It could have to do with how they used to (and still do) reduce the detail of polygons the further away they are from the player. When the player gets closer to the scenery then the extra vertices are added which causes the mesh to seemingly 'pop' at certain places. Also, from looking at the video they employ mip maps and fog which further reduces the rendering power required and which also contributes to the antiquated look of the game. Beyond that your guess is as good as mine.

---
Tags: graphics, textures, graphic-effects
---


# Question
Title: Render rotated rectangle inside other rectangle bounds using Libgdx
I have this code to generate a red rectangle inside a grey rectangle:

```
new Rectangle(grey_rectangle_position_x, Game.SCREEN_HEIGHT/2-Rectangle.height/2,0);

```

This code makes the following:

Now, I want to rotate the red rectangle and randomize his X coordinate but keeping it inside the grey rectangle.

This is my actual code of the rectangle:

```
public class Rectangle {

    public static int width=30;
    public static int height=60;
    public static Color color=Color.RED;

    public Rectangle(int x, int y, int angle) {
        super(x, y,angle);
    }

    public void render(ShapeRenderer shapeRenderer) {
        shapeRenderer.begin(ShapeType.Filled);
        shapeRenderer.setColor(color);
        shapeRenderer.identity();
        shapeRenderer.translate(pos_x+width/2, pos_y, 0.f);
        shapeRenderer.rotate(0.f, 0.f, 1.f, angle);
        shapeRenderer.rect(-width/2, -height/2, width, height);
        shapeRenderer.end();
    }
}

```

And this is what I should do to randomize the position of the rectangle:

```
new Rectangle(randomized_x_position, Game.SCREEN_HEIGHT/2-Rectangle.height/2,0);

```

The problem is that I don't know how to calculate the `randomized_x_position` in order to keep the rectangle inside the grey rectangle.

Another problem is that the current `Rectangle.render()` method is making my rectangle outside the grey rectangle after rotation:

When what I really want is:

# Answer
* Pick random angle(a)
* Compute AABB: http://willperone.net/Code/coderr.php

w' = h\*abs(sin(a)) + w\*abs(cos(a))

h' = h\*abs(cos(a)) + w\*abs(sin(a))
* Pick random positions so aabb fits inside bigger rectangle. p\_x \<= Width - w' p\_y \<= Height - h'
> 1 votes

# Answer
You have a two options. (1) You can either make sure your rotation doesn't move the rectangle outside the bounds, or (2) you can move the rectangle back after the rotation.

1. To rotate it without leaving the gray box, pick the top or bottom left edge. If it's the top choose a rotation less than 90 degrees that rotates counter clockwise, if it's the bottom choose a rotation less than 90 degrees that rotates clockwise. Then rotate by the chosen rotate around the selected corner. This will essentially pivot the rectangle by a corner that's already on the edge, ensuring it doesn't rotate outside the grey rectangle. Unfortunately this option limits your choices a good deal.
2. Moving it back inside the grey rectangle isn't too bad, and gives you a lot more flexibility. Essentially, you'll need to either find the bounds of the rectangle after rotation, or maintain the bounds through rotation. Maintaining the bounds would be something like keeping track of the points that make up the corners and rotating those points when you rotate the rectangle. Either way, you'll end up with the bounds of the rectangle, and then you can easily compare its edges to that of the grey rectangle. Allowing you to easily translate the rectangle by the difference.

The first option is easier to implement, but less flexible. The second option will be harder to implement, but far more flexible.
> 1 votes

---
Tags: opengl, java, rotation, libgdx, transformation
---


# Question
Title: Attribute ownership in Entity Component systems
How do you typically handle data ownership in these systems?

Right now I just have a map that maps type(std::string or hashed int)-\>void\* where outside sources can add attributes via a simple AddAttribute method.

Right now I'm having the problem of where and how to delete some of that data, since some of it is added via outside sources (e.g. reference to another entity) and some of it is legitimate data of the entity that contains it (e.g. health attribute).

The most obvious solution would be to simply use shared pointers, but somehow I'm worried that their overhead will become noticeable when I have a lot of entities (see https://stackoverflow.com/questions/3628081/shared-ptr-horrible-speed).

Another solution that I could come up with was to first use two distinct methods: "AddAttributeExternal" and "AddAttributeInternal" (or something similar, naming is irrelevant) where the attribute would only delete data that was added via the second. But I would like to avoid this since it introduces duplicate code and can probably be error prone when you introduce a lot of changing data.

Are there better/more optimized solutions or do I need to change the way I think about entity data altogether?

# Answer
> 2 votes
To make it more general than in the comments. There is nothing special in an ECS regarding memory management and object ownership. The same rules apply as to any other application.

Personally I'm an advocate of the most restricted version, clear object ownership and an explicit lifetime management for objects and memory in C++. Shared resource management *only* where it really has to be for instance for Audio-resources, Render-resources etc, but that is the exception. There is also the legitimate opinion that everything has to be smart-pointer-ed and we don't care about life time management. Each of both paradigms comes with its own set of problems, I will focus on the first one.

It basically comes down to a Fail-fast system vs. a Fail-safe system. Despite the names, in my experience the first one produces more robust code due to facing errors early and thus solving them is easier and less time consuming when it comes to debugging. Bugs will come in both version, the difference is the visibility, a good read on it is here.

So I would go with the easiest version, the responsibility over the lifetime of its attributes has the Entity. This goes for a health attribute as well as for a mesh or sprite or sound. They will make sure all resources that they need are available as long as they need it. If some of those resources are shared like Textures, then it makes sense to use smart-pointers for those special cases. Btw. I don't consider performance implications of smart pointers a valid argument in the discussion whether to use them or not. If you need the functionality they offer, then go for it. Just pick wisely *when* you need the functionality.

# Answer
> 0 votes
As Maik's answer says, the difference between reference data and value data (and how to manage the lifetime of references) presents the same challenges to any system that offers both types, and the use of components here doesn't really change anything. The main problem you have is that you're trying not to hard-code any types into an entity, which means you don't have the compiler helping you with distinctions between values and references.

In this situation I'd be tempted to treat everything on an entity as a value type that only lives as long as the entity does. These values could include references or names to long-lived objects elsewhere (eg. Entity IDs, textures, etc). Ideally you don't want every attribute being a reference type, eg. a pointer to an integer in the case of health.

How to manage their lifetime can be a bit trickier, but often you don't really need to delete anything during play and you don't need to worry about references outside of play, so it might suffice to load in all resources at the start of a level and free them at the end.

It's also worth noting that there's no intrinsic reason why you need to have an `AddAttribute` system that allows arbitrary properties. That level of genericity might be more trouble that it's worth, which is why many component-based systems have their modularity at the component level - ie. once you have successfully queried for a component, the system can be assured of the attributes that it contains (and can resolve references to them at compile time, in compiled languages).

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


title: Does Unity support 2D tiles/blocks?

text:
# Question
Title: Does Unity support 2D tiles/blocks?
I'm working on an XNA isometric game and I've already done lot of work. Since XNA is going to be discontinued, I'm not sure if I should change engines or not. So I'm looking into alternatives.

I'm already working on Unity for another game, a 3d game.

Question 1: Is it possible work with 2D tiles generation in Unity?

Question 2: Will building a 3D world based on Unity using tiles/blocks reduce the game performance?

# Answer
Unity doesn't have any real built-in support for 2D work. Compared to most 2D game development libraries and frameworks - eg. Pygame, XNA, Cocos2D, SDL, SFML - you will find it harder to write effective 2D games, especially tile-based ones. It is not as simple as *"3D, ignoring one dimension"* because of issues like texture management, texture bleeding, setting an orthographic camera correctly, avoiding seams in the rendering, and so on.

However, there are some add-on libraries you can get which help you with some of these issues. If you search the Unity Asset Store you will find some (paid and free) which you might consider using.
> 1 votes

# Answer
1. Yes, Unity supports 2D tiles. There are some tools (and free methods) for this and you can see it clearly by some of the 2D games made with Unity. And plenty of questions about it already on the Unity site.
2. This depends entirely on how it's implemented and the features you want to support. There are plenty of 2D games that are written using a 3D engine, they simply ignore the 3rd dimension. There may be low level optimizations you're missing out on by using a 3D engine, but you can easily achieve playable performance with a 3D engine.

All in all, this is something you'll need to research and find out the specifics of what you want to implement and what features you need to support with the technology at hand.

Additionally, just because XNA is being discontinued, does not mean it's going to disappear. There's still plenty of life left and unless you're waiting on a feature that XNA doesn't currently have, you'll be able to complete your game using XNA.
> 2 votes

# Answer
To answer your question, yes Unity can produce a 2d game. Its not entirely designed for a 2d game but since 2d is just a special case of 3d then... well you see where this is going. There are likely a number of toolkits that you can employ to make your 2d experience in unity a little easier.

That said, have you ever heard of MonoGame? It is an open source replacement for XNA which ... suprise suprise is crossplatform. So, if you dont want to have to learn an entire new paradigm of coding style ala Unity and you are quite comfortable with XNA then I would suggest you take a look at MonoGame.
> 2 votes

---
Tags: unity, tiles
---


# Question
Title: Perlin Noise for game terrain; math error (unexpected breaks in terrain (3D grid))
So, I'm learning how to generate terrain using Perlin Noise, and I came across this code: https://stackoverflow.com/questions/4753055/perlin-noise-generation-for-terrain/4753123#4753123

# PerlinNoise.h

```
    #pragma once

class PerlinNoise
{
public:

  // Constructor
    PerlinNoise();
    PerlinNoise(double _persistence, double _frequency, double _amplitude, int _octaves, int _randomseed);

  // Get Height
    double GetHeight(double x, double y) const;

  // Get
  double Persistence() const { return persistence; }
  double Frequency()   const { return frequency;   }
  double Amplitude()   const { return amplitude;   }
  int    Octaves()     const { return octaves;     }
  int    RandomSeed()  const { return randomseed;  }

  // Set
  void Set(double _persistence, double _frequency, double _amplitude, int _octaves, int _randomseed);

  void SetPersistence(double _persistence) { persistence = _persistence; }
  void SetFrequency(  double _frequency)   { frequency = _frequency;     }
  void SetAmplitude(  double _amplitude)   { amplitude = _amplitude;     }
  void SetOctaves(    int    _octaves)     { octaves = _octaves;         }
  void SetRandomSeed( int    _randomseed)  { randomseed = _randomseed;   }

private:

    double Total(double i, double j) const;
    double GetValue(double x, double y) const;
    double Interpolate(double x, double y, double a) const;
    double Noise(int x, int y) const;

    double persistence, frequency, amplitude;
    int octaves, randomseed;
};

```

# PerlinNoise.cpp

```
#include "PerlinNoise.h"

PerlinNoise::PerlinNoise()
{
  persistence = 0;
  frequency = 0;
  amplitude  = 0;
  octaves = 0;
  randomseed = 0;
}

PerlinNoise::PerlinNoise(double _persistence, double _frequency, double _amplitude, int _octaves, int _randomseed)
{
  persistence = _persistence;
  frequency = _frequency;
  amplitude  = _amplitude;
  octaves = _octaves;
  randomseed = 2 + _randomseed * _randomseed;
}

void PerlinNoise::Set(double _persistence, double _frequency, double _amplitude, int _octaves, int _randomseed)
{
  persistence = _persistence;
  frequency = _frequency;
  amplitude  = _amplitude;
  octaves = _octaves;
  randomseed = 2 + _randomseed * _randomseed;
}

double PerlinNoise::GetHeight(double x, double y) const
{
  return amplitude * Total(x, y);
}

double PerlinNoise::Total(double i, double j) const
{
    //properties of one octave (changing each loop)
    double t = 0.0f;
    double _amplitude = 1;
    double freq = frequency;

    for(int k = 0; k < octaves; k++)
    {
        t += GetValue(j * freq + randomseed, i * freq + randomseed) * _amplitude;
        _amplitude *= persistence;
        freq *= 2;
    }

    return t;
}

double PerlinNoise::GetValue(double x, double y) const
{
    int Xint = (int)x;
    int Yint = (int)y;
    double Xfrac = x - Xint;
    double Yfrac = y - Yint;

  //noise values
  double n01 = Noise(Xint-1, Yint-1);
  double n02 = Noise(Xint+1, Yint-1);
  double n03 = Noise(Xint-1, Yint+1);
  double n04 = Noise(Xint+1, Yint+1);
  double n05 = Noise(Xint-1, Yint);
  double n06 = Noise(Xint+1, Yint);
  double n07 = Noise(Xint, Yint-1);
  double n08 = Noise(Xint, Yint+1);
  double n09 = Noise(Xint, Yint);

  double n12 = Noise(Xint+2, Yint-1);
  double n14 = Noise(Xint+2, Yint+1);
  double n16 = Noise(Xint+2, Yint);

  double n23 = Noise(Xint-1, Yint+2);
  double n24 = Noise(Xint+1, Yint+2);
  double n28 = Noise(Xint, Yint+2);

  double n34 = Noise(Xint+2, Yint+2);

    //find the noise values of the four corners
    double x0y0 = 0.0625*(n01+n02+n03+n04) + 0.125*(n05+n06+n07+n08) + 0.25*(n09);
    double x1y0 = 0.0625*(n07+n12+n08+n14) + 0.125*(n09+n16+n02+n04) + 0.25*(n06);
    double x0y1 = 0.0625*(n05+n06+n23+n24) + 0.125*(n03+n04+n09+n28) + 0.25*(n08);
    double x1y1 = 0.0625*(n09+n16+n28+n34) + 0.125*(n08+n14+n06+n24) + 0.25*(n04);

    //interpolate between those values according to the x and y fractions
    double v1 = Interpolate(x0y0, x1y0, Xfrac); //interpolate in x direction (y)
    double v2 = Interpolate(x0y1, x1y1, Xfrac); //interpolate in x direction (y+1)
    double fin = Interpolate(v1, v2, Yfrac);  //interpolate in y direction

    return fin;
}

double PerlinNoise::Interpolate(double x, double y, double a) const
{
    double negA = 1.0 - a;
  double negASqr = negA * negA;
    double fac1 = 3.0 * (negASqr) - 2.0 * (negASqr * negA);
  double aSqr = a * a;
    double fac2 = 3.0 * aSqr - 2.0 * (aSqr * a);

    return x * fac1 + y * fac2; //add the weighted factors
}

double PerlinNoise::Noise(int x, int y) const
{
    int n = x + y * 57;
    n = (n << 13) ^ n;
  int t = (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff;
    return 1.0 - double(t) * 0.931322574615478515625e-9;/// 1073741824.0);
}

```

The properties I decided to use were:

* persistence = 1.0
* frequency = 0.1
* amplitude = 2.0
* octaves = 1.0
* randomseed = 1.0

Once I was able to get it running, I noticed a peculiar bug; plugging in these pairs creates a peculiar break in the terrain:

x | z

39 | 39

39 | 40

40 | 39

40 | 40

I then noticed that it appears the terrain creates a border, and generates a new seeded terrain. These new seeds begin at x = +40, and z = +40. Toying around with different seeds, I get the same effect. Sometimes I get multitudes of 7x7 squares that are completely different seeds. I'm not really sure what's happening. At first I thought there was some sort of 3 dimensional tangent going on, but I don't see any trig functions in the code.

This bug appears to occur no matter how I alter the properties.

I realize this is more of a programming question, but i was hoping to find someone more math oriented to see if they could deduce why my terrain (think 3D graph) has breaks in it. It's like they switch to a different method once I plug in more numbers.

Here's an example of my terrain bug. Im using these properties this time:

* persistence = 1.1
* frequency = 0.002
* amplitude = 10.0
* octaves = 6.0
* randomseed = 1.0

and the break happens at x = 77, z = 77

# Answer
The problem may lie here:

```
int Xint = (int)x;
int Yint = (int)y;

```

You want the floor value instead, or you will get discontinuities near zero:

```
int Xint = (int)floor(x);
int Yint = (int)floor(y);

```
> 2 votes

---
Tags: c++, 3d-meshes, debugging, perlin-noise
---


# Question
Title: Get timing correct with client side prediction
I believe I've got my head round CSP after reading Gabriel Gambetta's blog, Valve article and buildnewgames.com but having an issue understanding the time execution of everything.

So if a player holds the right arrow key down. I move the sprite by (speed * deltaTime) where deltaTime is the time between frames so speed is the same on differing frame rates.

My questions are:

1. Do I send a command to move right every frame?
2. How does the server correctly calculate this movement as it does not know the deltaTime of the client?

Really appreciate some guidance on this one. I'm using HTML5, javascript, node.js with socket.io.

# Answer
> 4 votes
Use a fixed time step to start. Fix Your Timestep

The server/client need to estimate the RTT (round-trip time) of the connection to correct times. The server is receiving commands from the (very recent) past. Its simulation needs to account for that. It knows where the client was and wanted to move to, not where the client is and wants to move to. The server needs to account for different clients potentially having very different RTTs.

Generally the server needs enough information to know where a client was X milliseconds ago to figure out bullet collisions and such.

Networking is hard. A *lot* of multiplayer hobbyist/indie/student games ignore most of the RTT issues by only claiming to support wired LAN play, where latencies are small enough to ignore for most games. Wireless and the Internet force you to deal with variable, large latencies that you have to work around to get satisfying play in an action game.

The Valve article covers that in a bit more detail. Ignore their advice on frame times; it's ridiculous.

# Answer
> 8 votes
## Do I send a command to move right every frame?

Sure. Why not? As long as the player is moving right, of course. If that's spamming the server too much, you could of course just send the command to move right and the command to stop moving right, but you're risking some troubling behavior if you miss the "stop moving" command. You could compromise between those two approaches. Send the command to move right periodically and send the stop command. Have the server keep moving right as long as it's received the command recently and stop when asked to stop OR when it hasn't received a keep moving right in a while.

## How does the server correctly calculate this movement as it does not know the deltaTime of the client?

The server shouldn't care about the internal delta framerate of the client. It SHOULD care about the time that a command is sent to it. If your game is sufficiently deterministic to allow for client-side prediction, then the relative frame-rates shouldn't matter. To be deterministic, for example, the server would need to know something like, what is the speed of this character. Here's what I mean:

The idea is the server has its own delta time. Here's an example, using minutes instead of milliseconds to make the concept more clear. Say I'm supposed to go 60 miles and hour. That's the same thing as 1 mile per minute. Lets say we were moving the car based on an elapsed time that varies. So we might get something like the following:

* 10 minutes. (Multiply 10 (minutes) by 1 (mile) means we move the car 10).
* 8 minutes. (Another 8 minutes have passed, so we move the car 8).
* 12 minutes. (12 minutes * 1 mile, add another 12).

So our total is 30 miles. Now on the server side, it might not be polling at the same times, but it's going to move the car the same amount if it's always multiplying the speed by the delta. So for example, say the server only polled every 15 minutes:

* 15 minutes (Multiply 15 (minutes) by 1 (mile) and we're at 15.)
* 15 minutes (do it again, we're at 30.)

Both the server and the client know the car has moved 30 miles, although they don't know the various delta frame rate of the other (and they don't need to know). Hope this example made it make sense.

## Implementation Strategy

Based on the comments below, I'd like to suggest the following strategy to implement client-side prediction: Start by not having any. Let the server handle where the location of the player. Send your commands, right left, etc., have the server calculate the position and then have the server reply back with the player's new location. On the client side, use the player location to set the location of the player. This will work, but it'll create some lag that you won't like. Now, attempt to do some client-side prediction. Update the client position with where you think the player should be before it hears back from the server. When it hears back from the server the actual location, update the player to actually be in that location (i.e., let the server "win" when they disagree). Now you can work toward letting your prediction code do a better of predicting correctly so that the end product results in minimum correction "jumping".

In short, right now some of your questions suggest you're struggling a bit with the basic set-up of having the server calculate player location. So break this down into steps, get that working first, and then work on the prediction code happening.

---
Tags: javascript, html5, multiplayer, node.js
---


# Question
Title: How to calculate size of object depending of its height on the screen?
I am programming a mostly 2D game on Android (with Andengine), but the player is a bouncing ball (kinda in 3D).

I wanted to make the bouncing of the ball the most realistic possible, using quadrilic equations (http://www.mathopenref.com/quadraticexplorer.html). So I know how to calculate the vertical height (z) of the ball, but I do not know, what size should the ball be, depending on its vertical height (z).

When the ball touches the ground, it should be 64px (width and height of the sprite), but if for example it is at 100px above ground, what should be the width and height of the displayed ball ? Is there an easy way to calculate it ?

Thanks

Game Dev noob.

# Answer
Remember one thing: Perspective projection ==== division by distance from camera. Let's say, that camera is at 0, so distance is Z coordinate of your object.

So your ball has X and Y coordinates equal to zero, it only changes the Z coordinate and you want to compute the **size** depending on Z. Let's say, your object is sliding between Z=100 and Z=10. First, you should find an absolute diameter **d** (size at Z=1)

for Z = 100, you decided, that **size** should be 64, so **d**/100 = 64, thus **d** = 6400

for Z = 10 : **size** = 6400/10 = 640

for Z = 200 : **size** = 6400/200 = 32

for Z = infinity : **size** = 6400/infinity = 0

Note, that larger Z (far away) makes **size** smaller and vice versa. If Z is 0 (disc on camera), **size** is infinite. If Z is negative, **size** is negative (or "behind the camera").
> 4 votes

# Answer
well there is ofc if you go into 3D calculations; but it sounds too me that try and error is enough. just set 2 different scales for 2 different height and interpolate. (eg. height: 0 = scale 64px; height 100 = scale 128) in case "kinda 3D" is isometric you don't need to scale it actually (but a shadow scaling on the ground might help)
> 1 votes

# Answer
I am making an assumption that you are viewing this ball from above for answering this question. Essentially, the size of the ball at a specific height depends on the viewing frustrum of your projection, and camera height relative to the ground(assuming once again that your view is pointing straight down the axis that you are using for 'vertical'). Using a perspective projection Matrix with a given view angle and aspect ratio, you should be able to transform a unit length vector (0,1,0) at ground location to get your base height, then whilst the game is playing, transform that same unit length vector at the current height of the ball (lets say 0,1,100) and the pixel size of the ball should be 64px * (length of transformed unit vector at 100height / length of transformed unit vector at 0 height).

Personally I would make sure your ball texture/sprite is higher resolution than 64px and use that for the sprite at the maximum height, and then scale it down to whatever size is required for height 0. You can then provide mip/maps for the sprite which should make your ball look great at any height.
> 1 votes

---
Tags: mathematics, perspective
---


# Question
Title: Is it normal that "Game.Run" in XNA uses a lot of resources?
I have been using the visual studio profiler to optimize my game. I have noticed that the `Game.Run` method is eating through 93.6% of the overall game resources.

Is this because all of the other functions are called by it in the game? Or is there a problem? I am quite new to the VS profiler and have in the past not used such applications to assist in optimizing.

# Answer
> 3 votes
Xna probably calls Present in it's body and this is just tells you that the application hangs 96% of the time waiting for the vertical sync -\> doing nothing. The task manager should report a low cpu usage too. It does not look like any optimization is necessary yet, at least not on the machine you are running it on.

Deactivating vsync should shift it to the Update/Draw functions.

---

**Question though is there any game performance advantage having the Vsync On?**

Vsync off basically leads to frames getting rendered that will not be displayed at all, as the display only updates in a fixed interval, most commonly 60hz. This wastes processing power/electricity and leads to presents getting issued while the display is receiving the last image which leads to an effect commonly known as tearing. On the other side activated vsync leads to an increased input latency of up to 1/fps seconds, which is very notable in some games, eg ego shooters, when using absolute input devices like a mouse or head tracking.

---
Tags: xna, optimization
---


# Question
Title: Getting started to OpenGL - little question
Im starting to learn opengl, and after 2 days, searching and trying hard, i finally installed all the libraries i need (lol).

So, I'm following this tutorial, and it says to use **glfwOpenWindowHint** this way:

```
glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); // 4x antialiasing
glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); // We want OpenGL 3.3
glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3);
glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL

```

But **glfwOpenWindow** didn't work with this Hint. So I made a little research, and changed the **PROFILE** parameter to this:

```
glfwOpenWindowHint(GLFW_OPENGL_PROFILE, 0);

```

Ok, fine, now works.

My question is if it is a big deal to change the opengl profile, or this will make no difference. And why I can't use **GLFW\_OPENGL\_CORE\_PROFILE** instead.

# Answer
OpenGL was divided into two profiles, `Core` and `Compatible`.

This was done to try to make OpenGL leaner, meaner and cleaner. The intent was to eventually deprecate the comparable profile but after some stink, the Graphics card vendors basically vetoed the idea and so developers simply have to option of using either.

What it comes down to is taste. Core doesn't have many unnecessary functions, and in a way forces you to use modern methods of doing things like vertex buffers. I see this as a positive because it trains you into using the faster, better ways of doing things, however it's also a HUGE negative if your just starting out.

Being able to do things the simple, old, but simple way makes learning GL way easier and as you figure it out and begin to learn the more complex topics you will begin to understand the advantages of using the modern approaches properly.

I say, stick with comparability for now but read into the differences and when possible try to utilize more modern ways of doing things.

In effect, consider the comparability profile like training wheels for a bike, you'd definitely want to start out with them, but eventually they might get in the way and limit performance.
> -3 votes

---
Tags: opengl
---


title: Torque2D, Class vs Datablock

text:
# Question
Title: Torque2D, Class vs Datablock
I'm scripting my first game with Torque2D and have not fully understood the difference between "Class" and `Datablock`.

To me it seems like `Datablock` is similar to a struct in C/C++ or a Record in Pascal. If I create `Datablocks` with keyword **new**, are they instantiated in the same way as a "Class"?

I have a large `TileMap` and need to attach some information to each Tile. I was thinking to use a `Datablock`, as a struct, to attach this information to the tile's `CustomData` property.

The two questions are: What is a `Datablock` and should I use a `Datablock` or a "Class" for this tile information?

# Answer
A Torque Script class is really not a class in terms of C++ classes. It is more or less a namespace grouping "class" member functions together.

```
function MyClass::MyFunction1(%param1)
{
  echo(%param1);
}

function MyClass::MyFunction2(%param1,%param2)
{
  echo(%param1 + %param2);
}

```

These two functions are in the same namespace aka Class, `MyClass`. We can call the functions as static members.

```
MyClass::Function1("Hello World"); // echo Hello World
MyClass::Function2(10,5);          // echo 15

```

Like in JavaScript, fields aka variables can be added to a collection of fields. But you can't add them to a static class. You must add them to an instance of the class.

There are two ways to get access to a "class" instance.

```
%MyObj = new ScriptObject();

```

`%MyObj` is a numeric integer value representing the instance handle. This handle can be used to access any members of the class. The second way is to create an object instead of an instance handle.

```
new ScriptObject(MyObj);

```

But why did we create a `scriptObject` instead of our `MyClass`?

You can't create classes that isn't defined and exposed in the Torque core (C++ source). All Torque classes are derived from the `SimObject` class and so are `ScriptObject` and it also defines some special fields.

```
%MyObj = new ScriptObject(MyObject)
{
  class = "MyClass";
};

```

Now we can call our functions from the handle because we told it to be class `MyClass`.

```
%MyObj.Function1("Hello World");

```

or from the object.

```
MyObject.Function1("Hello World");

```

Since `MyObject` isn't a variable, it shall not be accessed with the %

Well, not entierly true. Because we call it through its handle, the first parameter will always be the handle itself and is usually defined like this.

```
function MyClass::MyFunction1(%this,%param1)
{
  echo("Handle:" SPC %this SPC "Param:" SPC %param1);
}

```

The "instance" is passed in as the first parameter. It doesn't need to be called `%this`, but it has been the common practice to name it `%this`.

We can add fields as we please to this particular instance by just assigning values to it.

```
function MyClass::MyFunction1(%this,%param1)
{
  %this.Message = %param1;
}

function MyClass::MyFunction2(%this)
{
  echo("Handle:" SPC %this SPC "Param:" SPC %this.Message);
}

```

Okay so what are DataBlocks?

Let's say we have different configurations of `MyClass`. We can create a DataBlock for each configuration and then tell the instance to use it. All members of the DataBlock will be accessible fields in the instance.

```
datablock AudioProfile(audioName)
{
   filename = "~/data/sound/Audio.wav";
   description = "myaudioDescription";
   preload = false;
};

```

As for classes a `datablock` must be based on a predefined `datablock`. However, you can add new fields as you like to them.

```
datablock AudioProfile(MyAudioDatablock)
{
   filename = "~/data/sound/Audio.wav";
   description = "myaudioDescription";
   preload = false;
   Message = "My field";
};

```

Here we created a new `datablock` based on the `AudioProfile datablock` and added one extra field; Message. We can now create our class and add all the fields from the `datablock` at once.

```
%MyObj = new ScriptObject()
{
  datablock = MyAudioDatablock;
  class = "MyClass";
};

%myObj.Function2(); // echo My field

```

If we have the same class but many different configurations, we can create one `datablock` for each configuration and assign them when we create the class instance.
> 1 votes

---
Tags: tilemap, data-structure, scripting, torque
---


title: Selecting and moving vertices

text:
# Question
Title: Selecting and moving vertices
How can I identify the correct vertecis and move them in XNA using VertexBuffer? Let's say I have a simple cuboid in my project and want to move one face of it. How would I loop thru vertices, get their information and reposition those vertices to a new `Vector3` location?

This is a must for my project, since bones aren't flexible enough.

**EDIT:**

Since everyone is saying this would be bad and slow. Is there a way, again to loop thru vertecis, create a BONE and assign correct vertecis to it? Can this be done outside of content pipeline, during run-time (if not, content pipeline is ok)? How can I also then parent these bones to bones of THIS or OTHER model?

Also, if all of this works great and all. How would I then draw this model, I mean which transform or bone would I use for the world matrix? Especially if I had more than just one new bone.

# Answer
> 2 votes
So, first of all, let's say you're trying to resize a cuboid (and it will stay a cuboid). The correct solution in this case isn't to modify vertices or even to use bones. What you want to do is use a model matrix that specifies a scale. You can then scale your model on each axis to place the vertices where you want them.

---

But, let's say that you're sure that you need to modify individual vertices. And let's say that you want to move them independently and arbitrarily - in which case bones is *not* a good solution. (Bones would be good if you want to move *parts* of the model around - you don't want to have one bone per vertex!)

First, let's cover the easy bit: **How do you identify which vertices belong to a face?** You simply save the indices of those vertices when you construct your cuboid. For each face store a list of indices (`List<int>` or `int[]`).

Now let's look at **how to actually maintain and draw your vertex buffer**.

It's worth considering, at this point, that most people (including myself) are answering this question with an eye for performance. But if all you have is a cuboid - you could do just about anything and not suffer performance issues.

There are three "kinds" of vertex buffers in XNA. There's `VertexBuffer`, `DynamicVertexBuffer` and the various `DrawUserPrimitves` methods. I will give a very quick overview of how they work:

**`VertexBuffer`** allocates a section of GPU memory that the GPU reads vertices from. The GPU does some crazy pipelining stuff - it's possible for it to be drawing a frame long after you've started to draw the next one. So if you modify a `VertexBuffer` that is still being used to draw a previous frame, you stall the pipeline while the GPU finishes using the old data. Basically: Do not modify a `VertexBuffer` that is in use, if you can avoid it.

**`DynamicVertexBuffer`** works around this problem at the expense of GPU memory (and maybe some performance). Basically it allows the GPU to store several copies of your vertex buffer. That means that an older frame can use one copy, while your changes get applied to a different copy. There is also a `DynamicIndexBuffer`.

**`DrawUserPrimitves`** allows the GPU to assume that the vertex buffer won't get modified while it's still in use. The downside is that you are creating a new one each frame *and* must send the data for it to the GPU each frame. There is also an advantage, in some cases with small primitive counts, in that your data can be batched up with the the draw command, rather than copied separately.

---

Finally you must actually **get your data to the GPU**. I have a few important pieces of advice here.

First of all, you should *never* pull data back from the GPU, if you can avoid it. In XNA, that's the `GetData` method. It can potentially cause the GPU to pipeline flush *and* you're stalling your own program on the CPU, while it waits for the slow transfer of data from the GPU.

Given the above, **you should keep a copy of your vertex data as an array** (of your vertex type, eg: `VertexPositionColor`) in main memory. You can use this directly, modifying vertex positions (no need for a separate array of just the positions). Select elements in the array with the indicies you stored earlier.

Then simply use your array of vertex data with `DynamicVertexBuffer.SetData` (probably better - especially if you only change a section of the vertex data) before drawing the buffer, or with `DrawUserIndexedPrimitives` (probably easier).

If you do use `SetData`, for best performance you should try to minimise how many writes you do. For example, if you modify the face of a cuboid you only change 4 vertices. But those vertices may be spread out in the buffer - it is likely to be faster to set all 8 vertices of the cuboid, than to set 4 of them one at a time.

And, finally, it's worth pointing out that, no matter what option you choose, your data still has to get onto the GPU somehow! Using bones will not solve this problem. Bone transforms aren't exactly small - they get sent each frame (like `DrawUserPrimitves`) - so it's very possible for vertex data itself to be *smaller* if the number of bones is similar to the number of vertices. People are suggesting bones because it means you don't have to modify a `VertexBuffer` \- but as you can see from my answer, there are alternatives.

# Answer
> 2 votes
An actual VertexBuffer should really only be used for vertice information that wont be changing very often. When you assign a vertex array to a vertex buffer you are essentially moving the vertex info onto the gpu and receiving a reference to it that you can use to indicate to the GraphicsDevice that you will be using for the next render operation. If you want to be changing vertices around then you should really retain the original VertexPositionNormal array or whatever flavor of vertex data you are using and use a the DrawUserPrimitives or DrawUserIndexedPrimitives calls. The advantage of keeping the vertices as an array is that you can readily loop through them to identify if a face has been selected without having to call GetData first.

If you really want to modify a VertexBuffer then you will have to call GetData and then modify the the vertice info, and then call SetData with the modified array.

# Answer
> 1 votes
A vertex buffer is just as it sounds, a big list of vertex data, and you can frequently access this data by simply indexing the buffer. Changing the values stored in the vertex buffer will achieve the results you want of moving the vertex to a new position. You will have to develop a system yourself for skinning verts to bones, or at least identifying the vertex you want based on your search criteria.

# Answer
> 1 votes
Generally, you wouldn't do this. There are data structures designed for easy modification, such as those based on lists of half-edges. You would modify that data then regenerate the VertexBuffet rather than modifying the buffer directly.

The basic idea is to find all vertices belonging to the face (again, *much* easier with a data structure designed for it) and then moving them, splitting up any deformed polygons sharing those vertices (assuming it's not all triangles, which don't generally get into a deformed state).

Doing that with an optimized-for-GPU-rendering structure like a VertexBuffer is silly. You'll be copying the VBO back into memory (slow), doing a lot of iterating to find vertices matching some definition of a face, and then generating a new VBO. It's a lot of extra work for no gain besides a slight decrease in system memory by not needing the second data structure.

---
Tags: c#, xna-4.0, vertex, selection
---


title: What is XNA's GameTime used for?

text:
# Question
Title: What is XNA's GameTime used for?
I'm developing a game using fixed time step, and so far I haven't been using XNA's GameTime class in my code. What uses does the class have, and should I definitely use it in my game, or can I ignore it?

# Answer
You *can* ignore it if you want. Just be aware that XNA on Xbox and PC defaults to a fixed time-step of 60FPS, but Windows Phone defaults to 30FPS. By using `GameTime.ElapsedTime` you can ignore this difference.

It can also make your code clearer if you work in seconds or milliseconds (but please not both!). For example you might be specifying that an action lasts "30 frames", but it might be clearer to specify it as "0.5 seconds".

Just be aware that only `Update` runs a fixed number of times per second. `Draw` might get called a lot less frequently.

If you ever disable the fixed frame rate, then using `GameTime.ElapsedTime` is critical.

One very good reason you might want to disable it - at least during development - is for profiling. Possibly using a profiler (like the guy in this recent question) so that profiling time isn't spent waiting for the next frame. But also just to do simple frame-rate comparison profiling: maybe you get 100FPS normally and make some change - you get 90FPS afterwards, so it was a bad change. This is not possible if your frame rate is capped at 60FPS.
> 0 votes

# Answer
XNA (in fixed time mode) will try to call you 60 times per second, but that doesn't mean that the calls are always 1/60th of a second apart. GameTime will tell you how much time has elapsed since the last call, and you should use that to feed into any time-sensitive calculations.
> 3 votes

---
Tags: xna, fixed-timestep
---


# Question
Title: Unable to detect continuous keypress event in SDL
I am developing a game using SDL, and am unable to do continuous motion for my object when a key is held down.

I'm calling SDL\_PollEvent() to retrieve all events during a frame, and passing each resulting SDL\_Event structure into this function:

```
void Avatar::handle_input(SDL_Event keyInput){
if( keyInput.type == SDL_KEYDOWN )
{
    //Adjust the velocity
    switch( keyInput.key.keysym.sym )
    {
    case SDLK_LEFT: Move(1); break;
    case SDLK_RIGHT: Move(2); break;
    }
}

```

The problem is that when I hold down the right or left arrow keys, the avatar only moves once instead of moving continuously for as long as I hold down the key. How can I make the motion continue for as long as the key is held down?

# Answer
> 11 votes
An SDL\_KEYDOWN event is only sent when the key is first pressed. You will receive an SDL\_KEYUP event when it's released.

You'll want to handle moving in code which gets called every frame, not in response to an event. Inside Avatar::handle\_input, you'll instead want to set variables to tell you whether each key is up or down, and update those variables as you receive SDL\_KEYDOWN and SDL\_KEYUP events for those keys.

# Answer
> 4 votes
Trevor is correct, you actually need something like this:

```
// define vars somewhere
bool left_down;
bool right_down;

void Avatar::handle_input(SDL_Event keyInput)
{
    //If a key was pressed
    if( keyInput.type == SDL_KEYDOWN )
    {
        //Adjust the velocity
        switch( keyInput.key.keysym.sym )
        {
        case SDLK_LEFT: left_down = true; break;
        case SDLK_RIGHT: right_down = true; break;
        }
    }

    if( keyInput.type == SDL_KEYUP )
    {
        //Adjust the velocity
        switch( keyInput.key.keysym.sym )
        {
        case SDLK_LEFT: left_down = false; break;
        case SDLK_RIGHT: right_down = false; break;
        }
    }
}

// somewhere in the `update` function of game loop
update(/*...*/)
{
    if(left_down)
    {
        Move(1);
    }

    if(right_down)
    {
        Move(2);
    }
}

```

The code above does illustrates principle, but is hardly a way to implement it in a nice way. The better way is to have a keys array, which you can address like `keys[SDLK_LEFT]` and some universal utility functions.

More info is available directly from SDL docs.

# Answer
> 4 votes
An event is simply that - an event, and tells you when something has happened, not what the current state is. So you only get one keydown event, when the key first goes down, then a key up event when the key is released again.

For continuous motion, you have 2 choices:

1. Use the events to set your game's internal state. This is the example that Petr Abdulin gives in one answer here, which is an example of what Trevor Powell tells you in another answer.
2. SDL does actually provide a system for tracking which keys are in which state, and you can check this every frame if you want to implement continuous motion during key presses without tracking key states yourself. The function is called `SDL_GetKeyState` and the documentation is here. You can make these checks in your movement handling function and they should work as you expect.

---
Tags: sdl, input, events
---


# Question
Title: Checking collisions on isometric grids with offsets
I have a isometric grid with sprites that are placed in this sort of manner:

```
x: 5
y: 7
OffsetX: 5px
OffsetY: 10px

```

This is - what i want to do is when placing a new sprite, check to see if they collide, i can do it quite easily by just checking the `x` and `y` but the offset confuses me on how i can efficiently check for a collision.

Dose any one have any suggestions on neat ways to efficiently check collisions with offsets?

# Answer
> 2 votes
using the dimensions of your 2D sprite representing your isometric object doesn't sound like a solid idea to me. a long object along the x axis might has the same sprite width as an object which is wide along the y axis, but both might have different collision boxes.

I would treat those 2 values seperate and calculate collision using bounding boxes that approximate the dimension in isometric space. the offset makes sense because sometimes its not easy to approximate a box for your object. if you have a tree for example, the crown is going to be much bigger than the actual collisionbox which only includes the trunk, but you also want to have the sprite centered within the box and therefor you move the 2D sprite using your offset values.

The image above shows a large sprite (white), with a small collision box (blue) and some offset is used to center the sprite correctly.

Seperating your visual representation from the collision is the way to go in my opinion, even if objects can't be larger then 1 tile of your grid.

---
Tags: collision-detection
---


# Question
Title: Devices or Smartphones That Can Run and Displayed Images Properly While Power of 2 Code is Disabled
Before making game apps, I want to have any certain smartphone device brands that runs on OpenGL. I have to make a code for images that doesn't need to required power of 2 images so that I can resize the images independently from the start. However, some images appeared in white instead of the appearance that I expected like the old model phone *T-Mobile* on Android 1.6 for example after I disabled the power of 2 code. The only device I've known that worked and displayed image sprites properly is the *Google Nexus 7*. Can you tell me either other phone models that can display images without the need of power of 2 and will not display white images instead? Please give me an example at least. Thank you.

# Answer
> 2 votes
Well, AFAIK, OpenGL ES 2.0 supports non-power-of-2 (NPOT) textures, but only for certain configurations. Check this answer here for details on this:

https://stackoverflow.com/questions/11427010/opengl-es-2-0-texture-not-showing-on-some-device

For OpenGL ES 1.x, NPOT textures are not supported by default. There are various (mostly non-standard) extentions that allow you do to this but they are manufacturer/video-card/driver specific (i.e. for some Apple IOS 2 devices there's a GL\_APPLE\_texture\_2D\_limited\_npot that allows you to do that).

My advice is :

* if you don't really need to, don't use NPOT textures. Even if they do work, you can have big performance penalties because of this.
* if you absolutely have to use NPOT textures, code using the OpenGL ES 2.0 API only (no OpenGL ES 1.x). Most Android devices already support OpenGL ES 2.0 so you should be fine
* if you find yourself targeting a device that only supports OpenGL ES 1.x, check its video card specs to see if it has any extension allowing for NPOT textures (and if it does, check to see under which conditions that extension works, for example it can be that it will allow you to have NPOT textures, but not support mip-mapping on them, etc).

---
Tags: opengl, android, graphics, textures, libgdx
---


# Question
Title: When I create more than one boundary, every one but the most recent breaks
So basically what I have is a function called `createBoxBoundary`, which, when the player position is within certain limits, sets boundary variables to true. Pretty straightforward. However, when I call this function more than once in the main game loop, only the one most recently called works. Below is a sampling of my code

```
function createBoxBoundary(x,y,width,height){
    //right boundaries
    if(playerXPos + 40 == x && playerYPos + 80 >= y && playerYPos < y + height){
        boundaryRight = true;
    } else{boundaryRight = false;}

    //bottom boundaries
    if(playerYPos == y + height && playerXPos + 40 >= x && playerXPos <= x + width){
        boundaryTop = true;
    } else{boundaryTop = false;}

    //left boundaries
    if(playerXPos == x + width && playerYPos + 80 >= y && playerYPos <= y + height){
        boundaryLeft = true;
    } else{boundaryLeft = false;}

    //bottom boundaries
    if(playerYPos + 80 == y && playerXPos + 40 >= x && playerXPos < x + width){
        boundaryBottom = true;
    } else{boundaryBottom = false;}
}

```

I've also set up a **fiddle** with the full game code. And if anyone has advice on a better way to do collisions/boundaries in javascript, I'm open to that as well. Any help is appreciated!

# Answer
> 0 votes
I made the collision variables reset on each animation loop and then only set to true if they are a collision. I also changed the section of the code you call the animation loop from, this should be done after the processing of the current loop. Also added in some fallback support for my browser whilst testing. Updated fiddle here:

http://jsfiddle.net/totovste/QdCMG/8/

# Answer
> 1 votes
You set everything to false on a failed check and it looks a lot like you share those variables between all players/boundaries. might make sense to store them in an extra object and set/test each object individually.

---
Tags: collision-detection, javascript, html5
---


title: Rule / validation design pattern

text:
# Question
Title: Rule / validation design pattern
What design patterns can be used to create a rule / validation system for a game like chess (this is just a simple example, the actual game needs more difficult sets of rules)

I've read several questions on this site and haven't found a conclusive answer nor an answer pointing me in the right direction.

This system would require the following:

* Every object that has rules applied to it should implement a specific interface with a method that is the starting point for the validation
* The rule should be applied in 2 steps: first, it needs to be validated (can pawn A move to square D4), if true then execute method A if false then execute method B
* Every object can have multiple rules that need to be applied in a specific sequence. When rule 1 is finished, rule 2 should then start to validate etc
* Every separate rule (for example: can only move 1 square, can only move diagonally etc) must be in its own class and must be reusable and applicable on the objects that need rules.
* Note this is going to be used in a multiplayer game on the backend
* Note that every rule need multiple objects to test its validity, for example, normally a pawn can move 1 square, now the next sqaure on the gameboard is filled by a pawn of your opponent. Result: your pawn cannot move. The pawn should include the other pawns positions, or the gameboard in its validation.

Another word for these rules would be behavioral limits.

# Answer
> 3 votes
Think of a **game** as a sequence of **states**, separated by **moves**. Every time a player makes a move, a new state is generated.

<sup>(It's like this XKCD comic!)</sup>

# How

Create a class `Move`, which represents *one move made by one player*. (In Reversi, a sufficient description is one set of board coordinates where a piece is to be placed. In Chess, an origin and destination coordinate are sufficient.)

Create a class `GameState`, which represents the *state of the game at any one time*. (In Reversi, a sufficient description would be the board's contents and which player's turn it is. In Chess, you'd additionally need to store whether it is still possible for each player to castle kingside or queenside.)

Now, you can probably imagine the `GameState` having an `isMoveLegal(Move)` method. After all, it contains all the information it needs to make that decision.

# Why

This design cleanly isolates the rule logic, reducing inter-component dependencies.

It also makes AI easy! You can trivially generate all possible moves from a `GameState`, check if they're legal, generate more `GameState`s from those and basically build a tree that you can use for minimax, perhaps with alpha-beta pruning.

---
Tags: game-design, design-patterns
---


title: andEngine dynamic sprites

text:
# Question
Title: andEngine dynamic sprites
Ive just started with andEngine the past week and i only started learning java/android 3 weeks.

I can use a for loop to add multiple sprites to the screen but when i try to check collisions on them it only does it to one and not the rest.

I want to be able to add a specific number for sprites made from the same texture to the scene, add collision detection to them and also make them slide across the screen (im making a game where you avoid the obstacles).

My simple code:

```
private void createobstacle(float pX, float pY) {

    obstacle = new AnimatedSprite(pX, pY, this.mObjTextureRegion.deepCopy(),     getVertexBufferObjectManager());
    obstacle.setScale(MathUtils.random(0.5f, 3f));
    scene.attachChild(obstacle);
}

private void createobstacle(int num) {
    for(int i=0; i<=num; i++ ) {
        final float xPos = MathUtils.random(30.0f, (CAMERA_WIDTH - 30.0f));
        final float yPos = MathUtils.random(30.0f, (CAMERA_HEIGHT - 30.0f));
        createobstacle(xPos, yPos);
    }
}

```

Ive read about arrays but i cannot find any tutorials about anything im stuck with.

Any help would be great!

# Answer
The sample code you provided is not going to allow you to do collision detection or the like, because you're not holding references to multiple sprites--instead, you're replacing the same field. Let me give you an example that resembles your code, but simplifies the problem:

```
private int x;

private void setXRepeatedly(int count) {
    for (int i = 0; i < count; i++) {
        setX(MathUtils.random(10));
    }
}

private void setX(int amount) {
    x = amount;
}

```

If I ran this I would have no way of comparing one of the values of x with another value of x, because the older x value is constantly getting rewritten with no reference.

This is somewhat analogous to your code. Your createObstacle(int) method repeatedly calls your createObstacle(float, float) method, and the latter *repeatedly* sets the same obstacle field. So you're not holding a reference to multiple obstacles, you're only holding one.

## Arrays

One solution would simply be to use multiple fields. In my example above, instead of having just an x variable, I could have a y, a z, and so forth. A better approach would be to use an array, and an even better approach would be to use a java collection. First Arrays:

In my example code above, instead of using int x, I could declare an array of ints, like this:

> int\[\] myArray = new int\[10\];

This declares an array of ints and allocates memory for 10 of them. Now I could set individual ints in the array by putting the reference number in brackets. Like this:

myArray\[8\] = 5; myArray\[7\] = 2; etc.

So, in your example, we could have a declaration something like:

```
AnimatedSprite[] obstacles = new AnimatedSprite[10];
obstacles[0] = new AnimatedSprite(etc, etc.);
obstacles[1] = new AnimatedSprite(etc, etc.);

```

Note, arrays start counting at zero, not at one, and if you attempt to access or place data outside the bounds of what was allocated, you'll get an error. These and other reasons are why it often makes sense to use one of the java collections instead of an array.

## ArrayList Example

There are a number of different java collections with different feaures and benefits for different situations. An ArrayList is a handy simple one that avoids the problem described above of having to know the total size in advance. You create an ArrayList like this:

```
ArrayList<AnimatedSprite> obstacles = new ArrayList<AnimatedSprite>();

```

Now I can add objects to the ArrayList using the add() method, like this:

```
obstacles.add(new AnimatedSprite(etc.,etc.));

```

You can also call methods like these:

* get( int index ) - retrieves object reference from ArrayList index position
* size() - returns ArrayList size
* remove( int index ) - removes the element at the specified position in this list. Shifts any subsequent elements to the left and returns the element that was removed from the list.
* indexOf( Object o) - finds the index in this list of the first occurrence of the specified element
* clear() - removes all of the elements
> 0 votes

# Answer
You have add your all the required obstacles in to the list and in onManangeUpdate method of the sprite you can loop through. Check for collision and perform whatever thing you want.

While creation time:

```
obstacleList.add(obstacle);

```

While in onManageUpdate of the sprite:

```
for(int i=0;i<obstacleList.size();i++){
   if(Obstacle.this.collideWith(obstacleList.get(i))
        // do things you want
}

```
> 1 votes

---
Tags: andengine
---


# Question
Title: Programmatically creating billboards in unity
What is the most efficient way to render a billboard in Unity?

In order to apply a texture to something must it be a `GameObject` with a `Mesh` component? In which case, is my best bet to create a prefab of a Plane with the given texture and `Instantiate(...)` it at runtime? Or is there some sort of "billboard" primitive I should use instead?

# Answer
> 5 votes
**Update**

Unity version 4.3 now contains a new primitive type "Quad" which is the "2 triangle plane" described below.

---

You will want a 2 triangle plane ideally, generate the Mesh first then instantiate a new GameObject and supply the MeshFilter component with that programmatically generated mesh:

http://docs.unity3d.com/Documentation/Manual/Example-CreatingaBillboardPlane.html

This is a useful community script as well for camera facing billboards

http://wiki.unity3d.com/index.php?title=CameraFacingBillboard

Once you have generated the billboard as runtime drag it from the Hierarchy into the Assets panel to create a prefab for use in the future.

Alternatively use Blender or another external modelling software to create a 2 triangle billboard and use that... that would be the most efficient method.

---
Tags: unity, billboarding
---