title: Jelly ground collision

text:
# Question
Title: Jelly ground collision
For fun I am trying to replicate the mechanics from The Floor is Jelly. So far I have successfully created "jelly islands/blocks" which are represented by an array of points and then drawn by using quadratic curves between the points. I am also able to get the jelly effect by having each point hold a velocity value as well as a relationship with its neighboring points to allow the springyness effect.

The above works well and gives a good representation of how the actual game seems to do it.

The part that I am kind of stuck on is how to resolve collisions with the character. I can successfully detect when my character (currently just a square represented by 4 points) comes into contact with the jelly island. However, I cannot think of an efficient way to make it "stick" to the ground and then smoothly interpolate along the curve once a force is applied to the jelly that causes it to move. Also, I want the character to stick to the ground unless the user "jumps" which means that the character should follow the ground through it's wobbles rather than go up into the air.

I could pass the character controller the array of points representing the island that it is currently colliding with, but then iterating through all of the points and finding the points closest to the character seems like a lot of work to do on each frame. In addition I am still not sure how I would get the correct position of the character along the curved ground (particularly when it is wobbling).

Any suggestions are appreciated

## Update

Clarification as I fear that I wasn't clear enough above. What I mean when I say that I can successfully detect when my character comes into contact with the jelly island is that I am currently using the Point in Polygon algorithm to detect when the jelly island *is not moving/wobbling* this breaks of course once the jelly island has a force applied to it.

To fix this I have been looking into breaking the island into many line segments along the curves (how collisions with quadratic/bezier curves are usually handled), but I'm afraid that this will be too much work to do on each frame. In addition I am still stuck on the problems described above.

# Answer
> I could pass the character controller the array of points representing the island that it is currently colliding with, but then iterating through all of the points and finding the points closest to the character seems like a lot of work to do on each frame

When the collision first occurs you could save the id/index of the point in the array that is closest to the player. Then while the player is closest to this "center" point, you can just iterate over that point and the center point's neighboring points instead of all the points in the array. If the player moves away from the center point and is closer to one of its neighbor points, you can set that neighbor point as the new center point. If this works without glitching too much, then instead of iterating through each point in the array every frame, you'll instead just have to do a few distance checks every frame.

> In addition I am still not sure how I would get the correct position of the character along the curved ground (particularly when it is wobbling).

My guess would be that you need to store the x position of the character along normal straight ground and use that position to calculate what position of the curved ground that the character lines up with and should be at.
> 1 votes

# Answer
This is not something that you can cover in a question. To get proper results you need a physics engine that supports soft bodies collisions.

Use something like this.

Essentially the characters body is supposed to stick to the ground because it doesn't stop when it hits the ground. It's like a ball hitting a blanket, or a spring more precisely. So when the ball hits the ground, it looses some speed and the ground gains some speed. When the ground is pushed out of it's natural orientation it begins to apply more and more force in the opposite direction like a spring `F = -kX` where `F` is the force of the springy ground and `X` is the distance from the natural position of the ground segment. The last symbol, `k` is just about any number that you see fit. If it's small, the the ground is more stretchy and if it's large then the ground is almost rigid.

To detect collisions you don't need to break the curve into a million pieces. Very few pieces suffice to detect collisions reasonably. To speed up collision detection, place the segments and the character into a grid for fast collision detection.

Read about it here.
> 0 votes

---
Tags: 2d, collision-detection, physics, game-mechanics
---


# Question
Title: Questions about property-centric game object runtime
I was reading Game Engine Architecture by Jason Gregory

1. So according to him, I should use an array of entities, and arrays for each property, such as an array `gameObjectsPosition`, `gameObjectsHealth`... But in my case, the world is divided in a chunk grid. Each chunk have its own array (or for the moment vector but I plane to change that) of entities (game objects). Then, what should I do? Create a single array containing all entities positions wherever there are (and so one for health, level, orientations, dimensions...), or create the property specific arrays in each chunk?
2. Then how to process these property arrays? I mean, for each dynamic entity, I could update dimensions, sizes and health or I could for each property update each entity. Example:

```
 UpdateWorld() {
     for each entity in dynamicEntities
          entity.updatePosition()
          entity.updateHealth()
          entity.updateDimensions()
          entity.updateMesh()
 }

 UpdateWorld() {
     for each entity in dynamicEntities
          entity.updatePosition()
     for each entity in dynamicEntities
          entity.updateHealth()
     for each entity in dynamicEntities
          entity.updateDimensions()
     for each entity in dynamicEntities
          entity.updateMesh()
 }

```
3. How to handle sizes for each chunk? That'd mean each chunk have an array with `MAX_ENT_PER_CHUNK` (say in my example 1024), and then if a chunk have 24 entities there would be 1000 entities useless. Also, I can't use more than 1024 entities. I could use pointers, but then the CPU cache would hit a lot of misses.
4. How to handle IDs? If I have an array of entities I need to use IDs. I can use macro SID has specified in the book, but the IDs are not ordinals (they may not begin at 0)

# Answer
1. The code should serve the software engineer. Not the other way around.
2. The code should be written in the most intuitive and simple way it can be written (but not simpler).
3. Do not take advice unless you understand who it's intended for and what it's intended to resolve.

You are wearing a very uncomfortable pair of shoes because *someone said so* but do you understand why it was suggested in the first place, vs a dynamic array of Entity instances with data members like most moden oop programmers would write? It is there for very specific performance concerns that are unrealistic for most modern indie games.

You should ask yourself why you are doing things this way precisely. What do you wish to accomplish by following these guidelines? There is no point in moving away from the simple tested concept of a dynamic array (read Vector C++) or Entity instances with data members and methods relevant to those entities.

There is not one needed advantage that you pointed out for having an array for each property. It does not make any sense if you are an indie and not encountering some mysterious performance issues that you think you'll resolve by reducing the amount of cache misses you get.

In fact, the cache is pretty big nowadays. If you only access relevant entities at any specific time then it's likely you'll have plenty of cache to contain their data. Besides even if you do need to access memory, it is unlikely that will greatly reduce performance. Run some benchmarks and realize what you are so bent on achieving by writing less readable, and harder to maintain code, is possibly not worth your precious time. What do you actually want to make?

If we don't know what is the `X` you want to get, we can't understand why you wish to `Y` when it's clearly inferior and questionable for a lot of situations.
> 2 votes

# Answer
Try not to take the stuff you read in books too literally and apply concepts only where you think they really fit rather than just because you are trying to follow some pattern.

In my case I design my entities to have properties based on what makes logical sense.

I would not loop through every object in this manner because doing so per frame will get very costly very quickly. Instead look at using a component based event driven design for your code. When some condition is met (event occurs) on an entity update it.

You could event have different events resulting in different changes. So for example a "collision event" might result in a health drop but also may result in a position change.

Also I keep telling people this but: stop using arrays where you don't know how many things you have in a collection.

If I do this ...

```
var x = new Entity[1000];

```

The compiler will go and allocate me 1000 Entities worth of ram, but unless I definitely need 1000 Entities of ram right now this is a pointless waste of time and system resource. Use Lists or Dictionaries instead as their dynamic size means your code will only use the resources it needs.
> 1 votes

---
Tags: game-design, architecture, gameobject
---


# Question
Title: Basic 2d platform collision detection algorithm has a slight bug
I'm trying to implement collision detection between `Player` (the main character) and a `Platform`. They are both modelled as rectangles; when **player hits the side** of a platform he should bounce off it and when **player hits the top** of a platform he should glide (move) along it. The problem I'm facing is that sometimes the player bounces when he lands on top of the platform (near an edge) rather than glide along it.

For the collision detection, I'm using the Intersector class (LibGDX). If you are unfamiliar with this class, all it does is create the new rectangle that occurs when two rectangles intersect (i.e. the rectangle shaded green below).

Code:

```
for (int i = 0; i < list.size(); i++) {

    // An object from a list of objects that the player can collide with
    GameObject go1 = list.get(i);

    // True if the object is of type platform
    boolean playerPlatformCollision = (go1.getType() == ObjectType.PLATFORM);

    // If the two objects being compared are Player and Platform
    if (playerPlatformCollision) {
        Rectangle objectRect = go1.getRect();

        // If the Player and Platform overlap
        if (player.getRect().overlaps(objectRect)) {

            // The resulting rectangle from the overlap (as shaded green in the above pic)
            Rectangle intersection = new Rectangle();
            Intersector.intersectRectangles(player.getRect(), objectRect, intersection);

            // If the Player collides with bottom side of platform
            if (intersection.y > player.getRect().y) {
                player.setySpeed(-getySpeed()); // Make him bounce downwards
            }

            // If the Player collides with left side of platform
            if (intersection.x > player.getRect().x) {
                player.bounce(); // Make him bounce
            }

            // If the player collides with the top side of platform
            if (intersection.y + intersection.height
                < player.getRect().y + player.getRect().height)
            {
                player.setGravity(false);
                player.onPlatform(true);
            }
            else {
                player.onPlatform(false);
            }
        }
    }
}

```

Is there any sort of trick I can use for this? Haven't been able to find anything online that works.

# Answer
Yes, there is a trick you can use here. Based off of your glitch and your code sample, I'm assuming that you're moving both the player's X and Y position at the same time, then checking for collision.

Instead, move the player by its X velocity, then check for collision. If it has collided with any platform, then it must have hit the side of a platform. Take any action necessary for this collision, such as backing the player out of the platform and negating its X velocity.

After X velocity has been handled, you can now move the player by its Y velocity. If there is a collision, then it must have hit either the ceiling or the floor of a platform. Back the player out of the floor/ceiling, then set Y velocity to zero.

Hope this helps!
> 1 votes

# Answer
Found an easy solution to the problem. I just compared the midpoint x-coordinate of the player to the x-coordinate of the intersection to see where the player was relative to the platform (i.e. left or right). If the x midpoint of the player's rectangle \> x point of intersection rectangle, then he should be on top - otherwise, he's on the side of the platform. Changed the if statements for left side and top side to:

```
// left side of platform
if (intersection.x > player.getRect().x
    && player.rectangleMidPointX() < intersection.x) {
    // ...
}

// top side of platform
if (intersection.y + intersection.height < player.getRect().y + player.getRect().height
    && player.rectangleMidPointX() > intersection.x) {
    // ...
}

```
> 0 votes

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


# Question
Title: Frame independent buoyancy using Substepping
I am having trouble with a frame independent buoyancy force using substepping in Unreal Engine 4.

The original problem (which I am attempting to solve using substepping) is that when you apply a buoyancy force (which is proportional to the depth of the object), the force needs to change as the object rises out of the water. Consider the following, where an object is under water and we either have 2FPS or 42FPS (the curve representing the true force of the object as is rises)

Clearly the lower the framerate, the larger force is applied for too long resulting in the object accelerating too much.

Substepping alone does not fix this as the force being applied isn't recalculated every substep.

If I hook the force calculation into the substep then compare running at 60FPS and 10FPS I can see that at 10FPS I get 6 substeps every frame so I believe it should be the same.

However, I still see a discrepancy. That is, at 10 FPS the object leaves the water at almost double the velocity.

Some data from the 60 vs. 10 FPS runs

```
                       |  60FPS      |   10FPS
___________________________________________________
Velocity Leaving Water |  815 cm/s   |   1576cm/s
Time in water          |  0.89s      |   0.43s
Total displacement     |  122        |   41.84
Max Displacement       |  209cm      |   150cm

```

Here the time in water is measured by summing the dt's of each substep and the total displacement is the displacement at each substep multiplied by the dt.

I believe the problem is that the elapsed physics time is nearly double for the higher frame rate, though why this would mean the lower frame rate one comes out faster, I don't understand.

The code to apply the force is:

```
void UBuoyantPointComponent::CalculateBuoyancyPhysics(float DeltaTime, FBodyInstance* BI)
{
    // Data passed in from the main thread, now just reduced to the components offset which doesn't change
    PhysicsLock.lock();
    FPhysSubstepData LocalSubstepData = FPhysSubstepData(SubstepData);
    PhysicsLock.unlock();

    FTransform BodyTransform = BI->GetUnrealWorldTransform();
    const FVector& CalcCompLocation = (LocalSubstepData.ComponentOffset * BodyTransform).GetLocation();

    const float Altitude = CalcCompLocation.Z;
    const float Difference = 0.0f - Altitude;

    if (Difference > 0) // we are under the sea since the wave height is greater than the height of this point
    {
        float SubmergedVolume = FMath::Min(Difference, 100.0f) * 100.0f * 100.0f;

        FVector ComputedForce = ((FVector::UpVector * SubmergedVolume * BuoyancyStrength));
        BI->AddForceAtPosition(ComputedForce, CalcCompLocation);
    }
}

```

I can't even work out what I can try to gain more insight into this so any help would be greatly appreciated.

**Update**

Printing out data every substep reveals some interesting things that I didn't spot before. (Full log, the `---` indicates a game tick, each line is a substep tick). In summary though:

*The first set of substeps don't actually move the object at all*

This means after the first frame the 10FPS object is moving considerably faster than the 60FPS one since it has had a longer period of not moving and just accumulating force.

*dv calculation seems to be out by a half*

My `dv` which I think should be how much the velocity changes from to frame seems to be out by a factor of a half. It is being computed in the following way:

```
`DeltaTime * ((SubmergedVolume * BuoyancyStrength) / BI->GetBodyMass())`

```

Where `(SubmergedVolume * BuoyancyStrength)` is the only force applied to the object.

This discrepancy is magnified by the lower framerate and the objects speed increases twice a fast at lower depths (i.e. larger force) for longer.

# Answer
> 2 votes
I don't think there is much you can do to prevent this, because essentially your graph shows you the problem. The physics system has to apply the force according to the tick (or substep) delta, meaning that at some point it is just not possible to update the position of an object independent of the framerate.

That is also the reason why you can specify the max delta time for the physics tick and substep tick in your project settings (Settings -\> Physics -\> Framerate). Maybe try to lower these values to 0,01666 and 0,00833 (or even lower).

Another possibility would be to not use forces and just update the position directly depending on the elapsed time. Just whip up a sine-like function that uses the absolute elapsed time as input and gives you the object position in water as output. Then use this function to update your object position each tick. I know - it is not as nice, but it would be completely independent of the framerate.

---
Tags: c++, physics, unreal-4
---


# Question
Title: glsl uniform int as index of const array
I have a const array that define a few materials for directionnal light. I'd like to change the material using an uniform int as index of that array. Doing that leads to severe framerate drop.

I know that this could be fixed by just keeping the array in the cpu and send the material as uniform. But why does this not lead to framerate drop and the other do?

It seems that even with 2 elements in my array I have framerate drops. But accessing the array with a constant doesn't make me lag ( I presume glsl drivers optimize this by replacing the line with the correct element in the array ).

This is my shader :

```
struct Material
{
    vec3 ambiant, diffuse, specular;
    float shininess;
};

const Material materials[] = Material[]
(
    Material( vec3( 0.05375, 0.05, 0.06625 ), vec3( 0.18275, 0.17, 0.22525 ), vec3(  0.332741, 0.328634, 0.346435 ), 0.3 * 128 ),
    Material( vec3( 0.1, 0.18725, 0.1745 ), vec3( 0.396, 0.74151, 0.69102 ), vec3( 0.297254, 0.30829, 0.306678 ), 0.1 * 128 ),
    Material( vec3( 0.25, 0.25, 0.25 ), vec3( 0.4, 0.4, 0.4 ), vec3( 0.774597, 0.774597, 0.774597 ), 0.6 ),
    Material( vec3( 0.19125, 0.0735, 0.0225 ), vec3( 0.7038, 0.27048, 0.0828 ), vec3( 0.256777, 0.137622, 0.086014 ), 0.1 * 128 ),
    Material( vec3( 0.24725, 0.1995, 0.0745 ), vec3( 0.75164, 0.60648, 0.22648 ), vec3( 0.628281, 0.555802, 0.366065 ), 0.4 * 128 ),
    Material( vec3( 0.0, 0.0, 0.0 ), vec3( 0.5, 0.5, 0.0 ), vec3( 0.60, 0.60, 0.50 ), 0.25 * 128 ),
    Material( vec3( 0.05, 0.0, 0.0 ), vec3( 0.5, 0.4, 0.4 ), vec3( 0.7, 0.04, 0.04 ), 0.078125 * 128 )
);

void main()
{
    Material mat = materials[ index ];

    vec3 lightColor = vec3( 1.0, 1.0, 1.0 );

    float diffuseFactor = max( dot( normalize( Normal ), lightPos ), 0.0 );

    vec3 reflectedRay = reflect( -lightPos, normalize( Normal ) );
    float specularFactor = pow( max( dot( reflectedRay, normalize( cameraPos - Position ) ), 0.0 ), mat.shininess );

    vec3 ambiantColor = lightColor * mat.ambiant;
    vec3 diffuseColor = diffuseFactor * lightColor * mat.diffuse;
    vec3 specularColor = specularFactor * lightColor * mat.specular;

    color = vec4( ambiantColor + diffuseColor + specularColor, 1.0f );
}

```

# Answer
That would be because the GPU is optimized for massive parallel execution of the same program with multiple data, and accessing a non-constant index of an array in a shader (especially the fragment shader) does not count as "the same program" in GPU terms.

If you have seven materials, how about passing an array of seven floats, each defining a weight for each material, and mixing them instead using only one 1 and six 0s. Or in pseudocode, instead of doing this:

```
Material mat = materials[ index ];

```

You add a uniform array of seven floats like:

```
uniform float weights[7];

```

And then do this:

```
vec3 blend_ambient = vec3(0.0, 0.0, 0.0);
vec3 blend_diffuse = vec3(0.0, 0.0, 0.0);
vec3 blend_specular = vec3(0.0, 0.0, 0.0);
float blend_shininess = 0;

// If you're still having trouble, unroll this loop manually
for (float k = 0; k < 7; k++)
{
    blend_ambient += materials[k].blend_ambient * weights[k];
    blend_diffuse += materials[k].blend_diffuse * weights[k];
    blend_specular += materials[k].blend_specular * weights[k];
    blend_shininess += materials[k].blend_shininess * weights[k];
}

Material mat = Material(blend_ambient, blend_diffuse, blend_specular, blend_shininess);

```

If you want to use say, material 2, then you pass `weights` as `{0, 0, 1, 0, 0, 0, 0}`.

You will notice that this algorithm is much slower if you think in CPU terms, but is much faster in GPU terms.
> 1 votes

# Answer
Because your work would be done on the CPU, and not the GPU your framerates are unaffected. The more calculations you do in the shader, the more the GPU has to work. Some calculations are necessary such as applying transformations, since they can't be done at compile-time, but rather in run-time.

If anything, I recommend avoiding the declaration of const data because it's just a waste on the GPU side, when you can easily pass in the materials by uniform. What's more, is that if you pass by uniform you have to pass in the material before you render the object. To make use of uniforms, I recommend the following:

```
struct Material
{
 ...
};
uniform Material mat;

```

Then wherever you do the drawing, you would do something like:

```
id = glUniformLocation(prog, "mat.ambient");
glUniform3f(id, 0.1, 0.1, 0.1);

```

In the end, the choices are yours.
> 0 votes

---
Tags: opengl, glsl
---


title: What counts as a "game studio"

text:
# Question
Title: What counts as a "game studio"
I am registering a game on a site so that I can sell it, and it needs me to put in my game studio. I work on my games in c++ and I dont't have a team, or a company. Can I throw out a name and be done with it? or do I need to have a registered company?

# Answer
The simple answer is yes, unless the terms of service specify differently, you can just use any name you decide or simply use your own name.

However, if your games ever turn enough of a profit that it can no longer be considered a "hobby" then you must register as a business.
> 0 votes

# Answer
I have done such agreements in the past. Depending on where you live, an assumed title or company name may not be legally allowed. For all such agreements, I would put "independent" in that field.

However it's really best to consult with a lawyer who knows about the various laws surrounding this.
> 0 votes

---
Tags: publishing
---


# Question
Title: How to draw a mini map OpenGL & OpenGL ES?
I'm trying to draw a mini map. Succeeded to put current screen to smaller screen (mini map) via FBO.

But I do not know how to make the mini screen brighter when hover. You can imagine that, the real screen is very large, and you have a mini screen in the left bottom (like StarCraft), and when you hover on it, it's brighter than others.

I'm trying to use multiple attachment in FBO but it doesn't work. In fact that I don't know how does multiple attachment work, how is it used for?.

My way, draw map with attachment\_0 first, draw a hovering rectangle with attachment\_1. Bind then draw all of the attachment textures in legal sequence (NOT WORKED).

I mean, the first draws a mini "large screen".

The second draws a brighter rectangle when hover.

Can anyone lead me how to do this or give me any suggestion?

Thank you very much!

# Answer
> 1 votes
Multiple colour attachments are used for writing to more than one colour target from the same invocation of the fragment shader. That is, they are for fragment shader *outputs*.

A common use of multiple attachments is when you do deferred shading, where you may have one attachment for output position, one for output normal, one for output diffuse colour.

If you want to use multiple textures as *inputs* when drawing, you bind your textures to separate texture units and store the index of the units in your sampler uniforms. This is the same thing you do with a single texture, but as you use other texture units than 0, you may not have explicitly done so.

OpenGL has a set of texture units, named from GL\_TEXTURE0 up to some maximum. In the old days, each texture unit was sampled and the results combined in some manner by the fixed function pipeline. You select the active texture unit that `glBindTexture` shall affect with a call to `glActiveTexture(GL_TEXTURE0 + unitNumber)`.

Once you've got your texture ids bound to texture units, you can relate your sampler uniform variables in your shader with the texture units. If you have `uniform sampler2D mapTexture` in your shader, you would `glGetUniformLocation(prog, "mapTexture")` in your code to find the uniform, and `glUniform1i(that, N)` to indicate it should read from texture unit N.

For more details, consider reading a proper article like the arcsynthesis section on texturing.

The task you present, drawing a base image and something on top of it can be done in two ways:

* draw a quad textured with your base image, enable alpha blending, and draw a quad with your modification on top;
* draw a quad with a shader that combines the source texture with some modification, either from texture or programmatically.

---
Tags: opengl, maps, fbo
---


# Question
Title: How to get used Resources by State/Map etc?
I'm now managing the Loading of my Resources and I got a Question in my mind.

How does my Resource Manager know which Sprites,Sounds, etc. are used by the Map I want to load? First I thought of files which contain a list of used Sprites, Sounds etc. for every Map. E.g. like this

```
Map0001.map //Map Data
Map0001.sfx //List of Sounds
Map0001.gfx //List of Sprites
Map0001.tle //Tileset

```

This makes x4 more files than maps and I'm not sure if this is efficient, since every File has to be loaded and it's content read separately.

Any Idea on how to do this properly?

# Answer
> 1 votes
I personally just pack them into an archive file format.

Something as simple as the Quake .PAK file should be enough for this case. It's pretty simple to load and has tools that make packing files into them easier.

Here is documentation on the format, along with a C example (which is pretty simple to convert to Java).

If you want to compress the files, look into zlib Java bindings, and you could either append onto the .PAK file format to allow for compression or you could just use the .zip file format instead.

EDIT:

Apparently I misinterpreted the original post.

> I expressed myself wrong. Let's say my Map contains an enemy. How exactly does my Asset Manager know which file this Sprite uses, when it does not have access to the single Sprites within the Map?

You just store what's needed directly in the map file itself. When the AssetManager class loads the map, it should read in the portion of the file that contains a list of what's required. It's pretty efficient since everything is packed together in contiguous memory and can be read from pretty quickly. It's also really simple.

```
/*
   Pseudocode...
*/
struct map_asset_section_t
{
    uint32_t num_entites;
    uint32_t num_animations;
    uint32_t num_tilesets;

    hash32_t entities[num_entities];
    //... etc
};

```

---
Tags: java, resource-management
---


# Question
Title: How to handle pathfinding and path following with sprites the same size as the grid?
The game I am working on is currently using 32X32 collision boxes. I have implemented a working AI (A\* - path finding method) which is based on the Grid Size.

Lets say that I use that 16x16 grid , then if I try to implement a sprite to the AI, bigger than 16x16 the path finding will work but part of the sprite will go thru walls, because the AI follows the path generated by A\* for a 16x16 grid. Same rules applies if the grid is even smaller (8x8 for example). Is there a way to actually fix that problem. I do not know if that is possible, but if I could make the AI to include not 1 but lets say 4\*(8x8)boxes then I will have a one Big 16x16 square and I can use a 16x16 sprite picture(or bigger where the same rules apply). But then the A\* method should be tweaked.

The main idea is that I will create a Map in Tiled Editor with 16x16 grid , and then add collision 16x16 boxes (manually wherever I need them to be) which will be fed to an array with certain index numbers for each type of collision box (0,1,2 etc).So the bottom line is that I can not use sprites bigger than the collision box (or smaller will cause weird spaces). Am I missing something , or there are other ways of doing that ?

PS: also forgot to mention that if I make the collision boxes equal to the sprite size this won't work in the map, cause the collision wont be smooth or accurate enough

# Answer
The path you find with A\* and the path a unit travels do not have to be exactly the same path.

You can use methods like steering to follow paths found by A\*, while avoiding the corners of your obstacles. Or you can change the input to your A\* to allow it to find whatever kind of path you like (which can be followed directly). And you can find paths for units of whatever size you need.

You can use sprites of whatever size you like, as long as the steering algorithms know about the size and as long as A\* knows about their size.
> 0 votes

---
Tags: c++, sprites, tiles, sdl
---


# Question
Title: C++ Entity Component System: Diverse Behaviours
I'm trying my hand at an action RPG kind of game and using a modified version of entityx from alecthomas, which is basically an Entity Component System. I have really big troubles with some of the stuff I want to implement, because I don't know how to put it in terms of Components. Here are some of the things I can't figure out:

1. Let's say I have entities that are supposed to represent actors and they have things like Health, Stamina, Mana, Attributes... How would I implement a timed buff/debuff system, without defeating the purpose of ECS? Each actor can be affected by multiple buffs at a time and the buffs could influence anything about them. A component can only hold so much data and I can't introduce a new component for each buff that needs to save different data.
2. If I had a Chain Lightning skill that I cast with an actor and it selects and damages enemy actors at random immediately, the game-logic processor would just dish out the damage and create an entity for the Lightning Effect with a RenderComponent. But the RenderComponent will only tell the render processor that it is Lightning, where does the data go that describes which enemies were hit? Most skill effects have some kind of parameter for their renderable parts like Source, Target, Intensity...

Both questions are based on the same problem: How do I represent things that can have diverse parameters in as few components as possible?

# Answer
> 1 votes
Your first problem - why not have a component for each buff? They do similar things, sure, but many buffs might operate quite differently. For example, the simplest would be to increase the player's health by some amount. However, you may have a more complex debuff that say damages allies that are near the player every x seconds.

If you don't want to create a new component for each type of buff, then you could use the Decorator pattern. Decorators allow you to add functionality to a class without affecting other instances of that class. It works by essentially wrapping an instance of a class into a subclass of it, however it is done at run-time rather than compile-time like inheritance.

For your second problem it seems like you almost answer it yourself. It sounds like you will need Source, Target and Intensity components and your Chain Lightning skill when spawning the Lightning Effect should have those components. How that data is passed between systems is a design choice you will need to make for your ECS, perhaps through a message system. This means that components or entities should be able to send and receive data to and from one another.

The Lightning Effect entity could push a message up into your game loop like "Source:Player, Target:Enemy5, Intensity:10" which could be read by other entities, and processed if the message was meant for them.

---
Tags: c++, entity-system, entity-component
---


title: How do I destroy a SDL_Finger pointer?

text:
# Question
Title: How do I destroy a SDL_Finger pointer?
Hello I'm using SDL with C++ and I got this code:

```
void handleEvents() {
    SDL_Finger* finger = SDL_GetTouchFinger(SDL_GetTouchDevice(0), 0);
}

```

I do not know what SDL does inside the GetTouch function, maybe it allocates memory. Do I have to "destroy" finger here? Or will it be deleted by the end of the methods scope? Thank you.

# Answer
From a quick glance at the SDL wiki at the function you provided, it says:

"The returned resource is owned by SDL and should not be deallocated."

from - https://wiki.libsdl.org/SDL\_GetTouchFinger

Therefor, you shouldn't need to worry about destroying the object, SDL will manage it for you.
> 3 votes

---
Tags: c++, sdl, memory
---


# Question
Title: XNA - Update vertices property stored in a VertexBuffer
I've a class that creates a cube using VertexPositionColor and these vertices are stored in a VertexBuffer. Now i would like to dynamically change the color of my vertices. In my class i have a reference to a VertexPositionColor array wich contain all my vertices. I've wrote a SetColor function wich accept a Color in parameter and update each Color property of my vertices. But when i call it, it doesn't work. This is normal because vertices are stored in VertexBuffer and is not updated.

So, how can i update vertices property and keep using VertexBuffer?

# Answer
To change a vertex buffer it can't be active:

```
   GraphicsDevice.SetVertexBuffer(null);

```

To transfer vertex data to the gpu memory:

```
   VertexBuffer.SetData<VertexPositionColor>(VertexData);

```

To active the vertex buffer again:

```
   GraphicsDevice.SetVertexBuffer( VertexBuffer );

```

Note that if your color change affects every vertex with one unique color, you may consider to pass to a shader a single color as a parameter, and do not modify vertex.
> 3 votes

# Answer
The only way to change the contents of a VertexBuffer in XNA is by calling VertexBuffer.SetData().

When you need to update your vertex data often, it is recommended you use a DynamicVertexBuffer which streams vertices to the GPU.

Your best bet is to do some profiling using either:

* a DynamicVertexBuffer (stored in VRAM) and DrawPrimitives()
* a simple array (stored in RAM) and DrawUserPrimitives()

And see which one is faster **for your specific use case**.
> 1 votes

# Answer
I would do this using two vertex buffers. The first is static and contains the data that won't change, the second dynamic and containing the data that will change. That way you get to minimize the impact of data transfers. I'm not certain what the XNA equivalent of the relevant D3D terminology is, but GraphicsDevice.SetVertexBuffers looks to be what you need.
> 0 votes

# Answer
Like above suggestion made...

"Note that if your color change affects every vertex with one unique color, you may consider to pass to a shader a single color as a parameter, and do not modify vertex."

...if you do need to pass more than one color, I would suggest adding a texture parameter and then assigning the color in the effect file using something like...

pixelcolor=tex2D(samplerTexture,psIn.Coordinates);
> 0 votes

---
Tags: xna, vertex
---


# Question
Title: Organizing a Transform class to internally use quaternions
So, I'm interested in building a Transform class similar to the one used in Unity Engine, but in C++. My intent is for it to be user-friendly to change the position, rotation, and scale of a variable by specifying vec3s for each, where the rotation vector specifies Euler angles or some equivalent. However, the math library I have written uses quaternions, and I'd like rotations to be represented internally by quaternions. Since quaternions are a bit difficult to use on their own, or without an axis-angle conversion of some sort, I was wondering what's the best way to do this conversion somewhat efficiently on the fly, so the user doesn't need to fiddle around with quaternions? My current header file is as follows (I haven't written the implementation yet, aside from referencing the private global vectors to the public const ones):

```
class Transform
{
public:

Transform();
~Transform();

//// Local Information ////

// Position relative to parent
vec3 LocalPosition;

// Scale relative to parent
vec3 LocalScale;

// Rotation about x,y,z axes relative to parent
vec3 LocalRotation;

// Transformation matrix from worldspace to local space
mat4 WorldToLocal() const;

//// Global Information ////

// Position relative to world (const)
const vec3 &WorldPosition;

// Scale relative to world (const)
const vec3 &WorldScale;

// Rotation about x,y,z axes relative to world (const)
const vec3 &WorldRotation;

// Transformation matrix from local space to world space
mat4 LocalToWorld() const;

private:

vec3 _WorldPosition, _WorldScale, _WorldRotation;

// Stores rotation as a quaternion
// ??? Do I need one for global and local? How does this relate to rotation vec3? ???
quat _RotationRaw;

};

```

All help is greatly appreciated. I'm usually pretty good at solving these issues but I'm at a loss on this one.

**Edit:** Forgot to mention that I've read over the other GameDev Stack posts on the Unity Transform class, but I couldn't glean any info about this issue from them.

# Answer
> 0 votes
While you're right to use the quaternion as the underlying type for rotation, I'm concerned that you're exposing other fields in C++ which should be handled using getters/setters.

The convention for C++ is to expose get and set methods, and leave the particulars of how the field is handled to the class. That is, excepting TDA since this is a component, something like this:

```
public:
    set_EulerAngles(vec3);
    set_Rotation(quat);
    set_LocalPosition(vec3);
    set_Position(vec3);
    // +matching gets...
private:
    vec3 _WorldPosition, _WorldScale, _WorldRotation;
    quat _Rotation;

```

and is more like what Unity actually uses underneath:

```
private void INTERNAL_set_localRotation(ref Quaternion value);
private void INTERNAL_set_rotation(ref Quaternion value);
private void INTERNAL_set_localEulerAngles(ref Vector3 value);

private void INTERNAL_set_localPosition(ref Vector3 value);
private void INTERNAL_set_position(ref Vector3 value);

```

This frees you up to use alter how things are stored and which math is used later on.

Now, your set\_EulerAngles will look like (and I'm using C# here because my C++ is rusty):

```
var halfPitch = value.x * 0.5f;
var sinPitch = Mathf.Sin(halfPitch);
var cosPitch = Mathf.Cos(halfPitch);

var halfYaw = value.y * 0.5f;
var sinYaw = Mathf.Sin(halfYaw);
var cosYaw = Mathf.Cos(halfYaw);

var halfRoll = value.z * 0.5f;
var sinRoll = Mathf.Sin(halfRoll);
var cosRoll = Mathf.Cos(halfRoll);

_Rotation = new Quaternion();
_Rotation.x = ((cosYaw * sinPitch) * cosRoll) + ((sinYaw * cosPitch) * sinRoll);
_Rotation.y = ((sinYaw * cosPitch) * cosRoll) - ((cosYaw * sinPitch) * sinRoll);
_Rotation.z = ((cosYaw * cosPitch) * sinRoll) - ((sinYaw * sinPitch) * cosRoll);
_Rotation.w = ((cosYaw * cosPitch) * cosRoll) + ((sinYaw * sinPitch) * sinRoll);

```

and get\_EulerAngles would be something like:

```
var roll = Mathf.Atan2(2*(_Rotation.x*_Rotation.y + _Rotation.z*_Rotation.w),
                       (1 - 2*(_Rotation.y*_Rotation.y + _Rotation.z*_Rotation.z)));
var pitch = Mathf.Asin(2*(_Rotation.x*_Rotation.z - _Rotation.w*_Rotation.y));
var yaw = Mathf.Atan2(2*(_Rotation.x*_Rotation.w + _Rotation.y*_Rotation.z),
                      (1 - 2*(_Rotation.z*_Rotation.z + _Rotation.w*_Rotation.w)));
return new Vector3(pitch, yaw, roll);

```

---
Tags: c++, mathematics, design-patterns, transformation, logic
---


title: Custom key binding/mapping

text:
# Question
Title: Custom key binding/mapping
Currently I am starting to develop my first serious game. Before the games are all training, and learning how to do things in a good way. Unfortunatly, I've missed a big part in my preparation: Key binding.

Currently I am trying to figure out how I can bind keys to action for each scene in my game. For example: If the user presses the JumpButton during the GameScene, the avatar should jump, but pressing the same key in a MenuScene, the currently selected menuitem should be activated.

Which key the JumpButton is, should the user be able to set. But the behaviour should be always the same.

Here is my first, and I think very naviive idea:

I am having a HashMap with HashMap where Key is the key on the Keyboard and ACTION is just an enumValue. When I am in the scene, and a button is pressed, I will take that button, and ask the HashMap which action is bind to the button. using a switch I can now determine what to do. In my mind there is a little gap.. I have ONE action per Button, maybe named: ACTION\_PLAYER\_JUMP as an enumValue, and when I am in a GameScene this is okay, but in a MenuScene this ACTION\_PLAYER\_JUMP is not a very nice name... I do not want to have all bindings two times, just for better names.

Can someone tell me how to fix this, or a better system? I am sure there is a much better system for handling those bindings.

# Answer
> 1 votes
You should think of how to generalize this system so that any key can perform any action. Not only can the player customize their keys, but you might also want to enable different key behaviors between different menus.

You should be switching out the different keyboard mapping states when you switch scenes/to a new menu/etc. So when you enter a menu, the 'in-game' map values get removed and you add the 'in-menu' values. For this you could have previously defined lists of actions that are to be enabled/disabled at particular points eg:

RegularGameplay\[jump,run,moveForward,shoot\]

You can then call an enableSystems(List,bool) function that takes the list and adds/removes the actions on the list from the Map.

This sort of procedure becomes much more important as your game grows in complexity and different sections of the game require different specific mappings (specially when it comes to different menus).

I would however store something different in the hashmap values. You could have straight-up just a function pointer/delegate, and when a key is pressed you just call the function stored as a value for that key. You could also have an 'InputAction' class, and each action the user is able to perform is a new instance of this. An InputAction instance can hold things such as the function to call when the action is to be performed, a 'string' nice name to show the user, or even which key it's currently/should be mapped to (useful if the keys are customizable, so you know which key you should map an action on activation).

The base line is allowing for a particular subset of actions to be added/removed from your Map as the game state changes, and not try to have one single static map.

# Answer
> 1 votes
Your mapping strategy sounds like it'll work great. The problem you really need to solve is having pretty display names for your enum values.

See this question and answer on SO.

Essentially, you can switch from a `enum` or you can use C# properties to save and display additional information about each `enum` value.

Using either option, your dictionary is still going to use some kind of key mapping from a key code to an action. The dictionary is an ideal data structure for this kind of operation.

---
Tags: architecture, software-engineering
---


title: Cannot use DLL in my Unity project

text:
# Question
Title: Cannot use DLL in my Unity project
I'm pretty new in Unity and i'm trying to write reusable code to use across multiple "project". So I wrote this class to POST and GET highscore via WebRequest. I compiled the project to a DLL and added the DLL in my assets folder, and then I created a test script added to a GameObject opened it in VS2013 and created a reference to the DLL in the Assets folder, and now im trying to use it and it keep saying that the class name doesnt exist.

# Answer
A few items you will need to address for a dll to work in monodevelop:

1. Your class, constructor, and method in the dll must be public
2. You must use a .net compiler that is compatible with monodevelop (yours is) and the language must also be compatible. F# for example isn't.
3. Make sure to reference the assembly/dll in your references (i see you did in the screen shot)
4. Add 'using myclass' as the name from your dll into the header of the monodevelop cs script
5. Make sure any resources you are using in your dll are available and usable for monodevelop. If you are using another external dll (anything outside of the clr), it becomes a dependency for your dll and must be included as well.

Here is a handy reference from unity on the subject for more reading including how to debug a session between the environments. Otherwise reply with questions if this isn't enough detail to help with your issue.

http://docs.unity3d.com/Manual/UsingDLL.html
> 2 votes

---
Tags: unity, unityscript, dll
---


# Question
Title: Can I change shape of a rigid body after it created in Bullet3D?
I'm beginning Bullet3D. Can I change collision shape of a rigid body after it created? A rigid body accepts a collision shape when it's creating, but it's hard to find options changes the collision shape of an instance.

# Answer
There are `setCollisionShape()` and `setMassProps()` method for this on `btRigidBody` class.
> 4 votes

# Answer
As far as I know, you can't. You'd have swap out the entire rigid body object, I would imagine.
> 2 votes

# Answer
Here is how I've been able to do it:

1. Remove the rigidbody from the world.
2. Destroy the old shape(not sure if this is needed, but I do it for safe measure).
3. Create the newShape.
4. Use rigidbody.setCollisionShape(newShape). It is on the btRigidbody but is not in the API because it is an inherited from btCollisionObject.
5. newShape.calculateLocalInertia(mass, inertia).
6. rigidbody.setMassProps(mass, inertia).
7. rigidbody.updateInertiaTensor().
8. re-add the rigidbody to the world.

Depending on if your object is kinematic or has 0 mass, you might not need to do all the steps above, but I included them just in case.
> 0 votes

---
Tags: physics, bullet-physics
---


# Question
Title: Good way to support multiple types of triangles? (C# XNA)
\[this question is somewhat long. here's my question in a nutshell\]

I want to use multiple types of Vertex data types for my triangle, interchangeably. So if I have a generic type T

```
private void AddTriangle<T> (Vector3[] positions, Color[] colors = null, Texture2D texture = null)

```

And I identify T...

```
if(typeof(T) = typeof(VertexPositionColor){ ... }
if(typeof(T) = typeof(VertexPositionTexture){ ... }

```

How can I use T as if it actually *is* a VertexPositionColor or VertexPositionTexture? \[/nutshell\]

So in terms of types of vertices in C#/XNA, there's VertexPositionColor...

Then VertexPositionTexture, and VertexPositionNormalTexture, and VertexPositionColorTexture...

I'm trying to set up a system where I can create 3D worlds without much of a limit - I don't like limits. Nobody does, if I had to take a guess. My problem is that my methods, as well as lists, and rendering code all use "VertexPositionColor" hardcoded into the program. Even my triangle rotation method explicitly has "VertexPositionColor" typed in there. So suppose I had a list of VertexPositionTexture vertices that I wanted to use to render a model, in addition to all of the VertexPositionColor vertices used for other purposes. Is there a way I can easily switch between the four different types of triangles, without having to rewrite all of my methods and code hardcoded for each triangle type? (I'm not sure if generics would work here - it turned into a mess of type-casting, and I'm not sure if it's possible to restrict types)

Another question - how useful are the options? Within usual game development, is there ever really a use for VertexPositionColor vertices rather than VertexPositionTexture or VertexPositionColorTexture? Or is there a vertex type that is more versatile than the others?

EDIT: as requested, here's some of the code that has the VertexPositionColor hardcoded into it. I'd like to make the following code work for all vertex types, if possible:

```
    private void RotateTriangles(long TriangleID1, long TriangleID2, Vector3 AroundPoint, Vector3 Rotation, string Key)
    {
        float Sine1, Cosine1, Sine2, Cosine2, Sine3, Cosine3;
        Sine1 = (float)Math.Sin(MathHelper.ToRadians(Rotation.X));
        Cosine1 = (float)Math.Cos(MathHelper.ToRadians(Rotation.X));
        Sine2 = (float)Math.Sin(MathHelper.ToRadians(Rotation.Y));
        Cosine2 = (float)Math.Cos(MathHelper.ToRadians(Rotation.Y));
        Sine3 = (float)Math.Sin(MathHelper.ToRadians(Rotation.Z));
        Cosine3 = (float)Math.Cos(MathHelper.ToRadians(Rotation.Z));
        long TriI = TriangleID1;
        long point;
        float tmp;
        VertexPositionColor[] vertices = triangleData[Key].ToArray();
        while (TriI <= TriangleID2)
        {
            point = 0;
            while (point < 3)
            {
                tmp = vertices[TriI * 3 + point].Position.Z;
                vertices[TriI * 3 + point].Position.Z = AroundPoint.Z + ((vertices[TriI * 3 + point].Position.Z - AroundPoint.Z) * Cosine1) - ((vertices[TriI * 3 + point].Position.Y - AroundPoint.Y) * Sine1);
                vertices[TriI * 3 + point].Position.Y = AroundPoint.Y + ((tmp - AroundPoint.Z) * Sine1) + ((vertices[TriI * 3 + point].Position.Y - AroundPoint.Y) * Cosine1);

                tmp = vertices[TriI * 3 + point].Position.X;
                vertices[TriI * 3 + point].Position.X = AroundPoint.X + ((vertices[TriI * 3 + point].Position.X - AroundPoint.X) * Cosine2) - ((vertices[TriI * 3 + point].Position.Z - AroundPoint.Z) * Sine2);
                vertices[TriI * 3 + point].Position.Z = AroundPoint.Z + ((tmp - AroundPoint.X) * Sine2) + ((vertices[TriI * 3 + point].Position.Z - AroundPoint.Z) * Cosine2);

                tmp = vertices[TriI * 3 + point].Position.X;
                vertices[TriI * 3 + point].Position.X = AroundPoint.X + ((vertices[TriI * 3 + point].Position.X - AroundPoint.X) * Cosine3) - ((vertices[TriI * 3 + point].Position.Y - AroundPoint.Y) * Sine3);
                vertices[TriI * 3 + point].Position.Y = AroundPoint.Y + ((tmp - AroundPoint.X) * Sine3) + ((vertices[TriI * 3 + point].Position.Y - AroundPoint.Y) * Cosine3);

                point++;
            }
            TriI++;
        }
        triangleData[Key] = vertices.ToList();
    }
    private void AddArrayToDictionary(string Key, VertexPositionColor[] array, int[] vertices = null)
    {
        List<VertexPositionColor> fixedlist = array.ToList();

        if (!triangleData.ContainsKey(Key))
        {
            triangleData.Add(Key, new List<VertexPositionColor>());
        }
        triangleData[Key].AddRange(fixedlist);

        if (vertices != null)
        {
            List<int> indexdata = vertices.ToList();
            if (!indicesData.ContainsKey(Key))
            {
                indicesData.Add(Key, new List<int>);
            }
            indicesData[Key].AddRange(indexdata);
        }
    }
    private void AddTriangle(Vector3[] vertices, Color[] colours, string Key, bool Indices_On)
    {
        if (!triangleData.ContainsKey(Key))
        {
            triangleData.Add(Key, new List<VertexPositionColor>());
        }
        for (int i = 0; i < vertices.Count(); i++)
        {
            VertexPositionColor check = new VertexPositionColor(vertices[i], colours[i]);
            if(!triangleData[Key].Contains(check) || !Indices_On)
            {
                triangleData[Key].Add(check);
            }
        }
    }

```

And here's the structure I'm using for my triangle vertices:

```
    Dictionary<string, List<VertexPositionColor>> triangleData = new Dictionary<string, List<VertexPositionColor>>();
    Dictionary<string, List<int>> indicesData = new Dictionary<string, List<int>>();

```

And finally, here's my draw code:

```
    protected override void Draw(GameTime gameTime)
    {
        RasterizerState rs = new RasterizerState();
        rs.CullMode = CullMode.None;
        rs.FillMode = FillMode.WireFrame;
        device.RasterizerState = rs;
        device.Clear(Color.DarkSlateBlue);
        effects.CurrentTechnique = effects.Techniques["ColoredNoShading"];
        effects.Parameters["xView"].SetValue(Game_Camera.view);
        effects.Parameters["xProjection"].SetValue(Game_Camera.projection);
        effects.Parameters["xWorld"].SetValue(Matrix.Identity);
        foreach (EffectPass fxpass in effects.CurrentTechnique.Passes)
        {
            fxpass.Apply();
            device.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, triangleData["Landscape"].ToArray(), 0, 5, indicesData["Landscape"].ToArray(), 0, 2, VertexPositionColor.VertexDeclaration);
        }

        base.Draw(gameTime);
    }

```

# Answer
This question seems to be an X/Y problem. I think what you are really asking "how do I rotate a set of triangles?" You've settled on a very slow, very wrong solution to this problem. **You should never be directly modifying vertex data on the CPU, unless you absolutely have to**. I think your answer boils down to replacing:

```
effects.Parameters["xWorld"].SetValue(Matrix.Identity);

```

With:

```
effects.Parameters["xWorld"].SetValue(RotationMatrix);

```

Where

```
RotationMatrix = Matrix.CreateRotationX(Rotation.X) *
    Matrix.CreateRotationY(Rotation.Y) *
    Matrix.CreateRotationZ(Rotation.Z) *
    Matrix.CreateTranslation(AroundPoint);

```

Also, to answer your original question, generics can work. All thats needed is a guarantee that the type `T` contains the element `Position`. You can force `T` to be of a particular type or interface in this way:

```
public void FunctionName<T>(...) where T : OtherType

```

That said, the best way to get around this is to *not store the vertex structs directly* if you're going to generate/operate on them. Instead, convert from the **raw** data. Do this:

```
Dictionary<string, List<Vector3>> positions = new Dictionary<string, List<Vector3>>();\
Dictionary<string, List<Color>> colors = new Dictionary<string, List<Color>>();
Dictionary<string, List<Vector>> uvs = new Dictionary<string, List<Vector2>>();
Dictionary<string, List<int>> indices = new Dictionary<string, List<int>>();

```

Or better yet, make a class for a Mesh that contains all of these:

```
class Mesh
{
    public List<Vector3> positions;
    public List<Color> colors;
    public List<Vector2> uvs;
    public List<int> indices;
    public VertexBuffer buffer;
}

```

Then, when you populate the vertex buffer, interpret the type based on an enum, or just the presence/absence of each of these fields.
> 3 votes

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


# Question
Title: Rotate on key down, revert rotate on key up?
How would I rotate an object a certain number of degrees when the left arrow is pressed and then rotate it back to its start when the left arrow is released?

# Answer
You may want to look into this and this. Unity makes it really easy.

The scripting reference is your best friend.

Something like the following:

```
if (Input.GetKeyDown(KeyCode.LeftArrow))
    transform.rotation = Quaternion.Euler(0, 30, 0);
else if (Input.GetKeyUp(KeyCode.LeftArrow))
    transform.rotation = Quaternion.identity;

```
> 1 votes

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


title: Paint game level algorithm

text:
# Question
Title: Paint game level algorithm
I have a game, and I have a level editor where you can build your level from blocks. Blocks positioned in cells. So blocks can have no neighbours or have one or few neighbours. My problem is that I need to put appropriate texture to block, based on block position related to another blocks. Is there some specific algorithms or methods that can help me?

I want it to update textures after adding/moving/deleting each block so it should be fast.

Levels can look like

```
- - - - - - - - - - - - - - -
|                            |
|             |- - - |       |
|             |- - - |       |
|                            |
|         - - - - -          |
|         |       |          |
- - - - - |       | - - - - -|

```

# Answer
Use a bitmask to determine which graphic you want to use, see this article When you have neighbouring blocks of the same kind, simple change the bitmask and this bitmask is used for drawing the Tile. http://www.angryfishstudios.com/2011/04/adventures-in-bitmasking/
> 2 votes

---
Tags: algorithm, tile-bitmasking
---


# Question
Title: Pick which directional light shades which object
Suppose you have two directional lights pointing at one sphere from different angles. You would expect the sphere to cast two shadows, but it turns out that this isn't the default behavior. The first light in the scene is the only one that casts a shadow. I want all my yellow spheres to take shadows from light A, but I want all my blue spheres to take shadows from light B instead of A. Is there a way to do this?

(It seems there's a fullforwardshadows pragma that could make the spheres cast both shadows. I'll try to figure that out if need be, but I really only need one shadow per sphere.)

# Answer
Yes, you can configure your Lights to affect only certain objects, by using Layers.

Assign your objects to a specific Layer (you can use an existing layer or define your custom one). Then, in Inspector pane, use Light's **Culling Mask** setting to set which Layers you want it to affect.
> 1 votes

---
Tags: c#, unity, shaders, shadows, shadow-mapping
---


# Question
Title: MonoGame InstancePlayLimitException on Windows w/ OpenGL
Why am I getting the **InstancePlayLimitException** when playing several **SoundEffects** per second despite there being no limit unless programming for mobile? It occurs after only a few seconds of repeated playing. I am using Visual Studio 2013 and MonoGame 3.2.

# Answer
> 1 votes
Make sure your build target is set correctly. If that is, then attach a debugger to your code. Wrap your sound code in an exception handler and examine the conditions that led to the exception being thrown. With this information, you can either code to avoid those conditions, or depending on the conditions, modify MonoGame to ignore the exception.

---
Tags: c#, monogame, sound, visual-studio, exceptions
---


title: Vector2 to 3D world coordinates

text:
# Question
Title: Vector2 to 3D world coordinates
I think I am almost there, but not quite. I am trying to transform a 2D point, (in the following example **(100,100)**) into 3D world coordinates, in order to draw my 3D Model named `TestModel` in XNA/Monogame. Here is my attempt:

```
Matrix[] transforms = new Matrix[TestModel.Bones.Count];
TestModel.CopyAbsoluteBoneTransformsTo(transforms);
ModelMesh mesh = TestModel.Meshes[0];
BasicEffect effect = (BasicEffect)mesh.Effects[0];
float Scale = 1.2f;

effect.View = Matrix.CreateLookAt(new Vector3(0.0f, 0.0f, 6115.0f),
     Vector3.Zero, Vector3.Up);
effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
    aspectRatio, 1.0f, 10000.0f);
effect.EnableDefaultLighting();

//here i am using the function to calculate the world coordinates from (100,100) Point
//it gives me modelPosition = {X:284,0316 Y:384,2054 Z:0,9999364} in this example
Vector3 modelPosition = graphics.GraphicsDevice.Viewport.Project(new Vector3(100, 100, 1),
   effect.Projection, effect.View, Matrix.Identity);

effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateScale(Scale) *
   Matrix.CreateTranslation(modelPosition);

//finally i draw the model
mesh.Draw();

```

I suppose this is the correct function to do it `graphics.GraphicsDevice.Viewport.Project`, so what exactly am I missing here ? Right now the model is drawn around **(393, 444)** in the 2D world (instead of (100,100) which is where i am trying to draw it)

Edit: I had wrong numbers before
Edit2: I think the correct function is Unproject, but i still can't get it drawn at (100,100)

# Answer
> 1 votes
You are right that the correct function is Unproject. Try this:

```
Vector3 modelPosition = graphics.GraphicsDevice.Viewport.Unproject(
    new Vector3(100.0f, 100.0f, 0.01f), // Note the 0.01f!
    effect.Projection,
    effect.View,
    Matrix.Identity);

```

The 0.01f means you want a point that is 1% of the way between your near and far clip planes (the values you passed into `Matrix.CreatePerspectiveFieldOfView`). This will work out to `1.0f + 0.01f * (10000.0f - 0.01f) = 100.99f` away from the camera position. It should be centered at pixel position (100, 100). Try decreasing the 0.01f value or decreasing your far clip plane distance if the model is too small or not visible.

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


# Question
Title: Object orientated design for RPG character creation
This question may not be helpful to some but I'll ask anyway. I've hit a bit of a object orientated design issue. Making a RPG and the user gets to choose their own class i.e warrior/rogue/etc.

Sample:

```
int main()
{
    CharacterP *cPntr = new CharacterP // creates base pointer
    cPntr->createClass(cPntr, "Warrior"); // creates a new Warrior object which cPntr is now
                                           //pointing to.

    cPntr->printCharacterName();  //will print the warriors print name function

    return 0;
};

class CharacterP
{
    void createClass(CharacterP* &samp, string choice)
    {
        if (choice == "Warrior")
            samp = new Warrior;
         // other classes go here...... i.e Rogue, Mage
    }

    virtual void printCharacterName() //I don't want this function here
                                      //as this function will never be used, however it is
                                      //needed as the type of pointer for cPntr is CharacterP
                                      //which is the base of warrior.
    {
        std:: cout << "i don't want this function here, although it is required;
    }

};

class Warrior : public CharacterP
{
    virtual void printCharacterName()
    {
        std::cout << "you printed warrior";
    }
};

```

The main problem is the way I've designed this: If I want to use a `Warrior` function, I also have to define it into the base class `CharacterP`. When i start branching this out and adding more classes i.e Mage/rogue its going to be a maintenance nightmare as the base class would have a lot of functions that won't be used at all.

**Questions:**

Why does this happen?

Why does the base class also need to have the same function even though the derived function is virtual?

What is a more efficient way of doing what i am doing? (giving the user the ability to create any classes they want i.e Warrior,Warrior,Mage/Rogue,Mage,Mage) maybe a way to create a warrior object with its own pointer which can be repeated so 3 warrior objects are created and can be used at runtime.

# Answer
> 2 votes
The questions you should be asking yourself is if it makes even sense to treat different *character* classes as different *code* classes.

You usually use code-classes when you have objects which behave differently in terms of programming. But in many games, this isn't actually the case. Fighter, Warrior, Knight and Barbarian all can use the same programming, but only have different stats. These stat templates are better represented by instances of one code-class `CharacterClass` where each instance carries the data about how this character-class differs from the others. Your `PlayerCharacter` class would then reference the `CharacterClass` which applies to the character.

You could hardcode the stats of each `CharacterClass`, but it might be better to read this information from external config files for better maintainability.

When you have more different character-classes with notable differences in game mechanics (warriors, mages, archers, clerics...) it might still be possible to put them all into one code-class and instead extract their character-class features into individual code-classes. Each `CharacterClass` might have a list of `CharacterClassAbility`s which are available to characters of that character-class. Examples for such class abilities would be `MeleeAttack`, `RangedAttack`, `MagicAttack`, `PickLock` or `CureLightWounds`. When your game features a progression mechanic where the character-class abilities are unlocked progressively, the information which abilities are already unlocked would be stored in `PlayerCharacter`, not in `CharacterClass`, because multiple characters can share the same character-class.

You might notice that this system easily allows you to create hybrid character-classes like "Spell Sword" which combines some of the character-class abilities typical to mages with some of the character-class abilities typical to warriors.

# Answer
> 0 votes
There is nothing wrong with the approach of defining the methods in the base class. In other languages, we would use interfaces for this, however this does not work in C++.

You should make your base class abstract and define the methods as abstract as well. This way you do not need to implement them in the base class.

```
class CharacterP
{
   void PrintName() = 0;
   void Walk() = 0;
   void Die() = 0;
}

```

As an additional benefit, you just have to take a look at your base class and know the features of the derived class. Being abstract, the methods force you to re-implement them when creating a new 'class' class.

Edit: The keyword in this context is 'polymorphism'. Have a look at it!

# Answer
> 0 votes
I think an important question is whether your character IS A warrior-rpgclass, or HAS A warrior-rpgclass

with an IS A relation, you would make the Warrior class inherit from your CharacterP class.

with a HAS A relation, you would give the CharacterP class a property called "Class", which holds an object of the Warrior class (which could inherit from a base Class abstraction)

a good principle for OOP is to favor composition over inheritance, as it allows for easier maintainability down the line.

# Answer
> 0 votes
I am working on a similar problem (granted I am using a different language so I'll try to only focus on principle). I basically made just a function for each part of the player that could be different at any point in the game and gave it conditions that would just add to the player's stats (I.e. Shield could be none, paper, glass, wood, or metal. Each different type added a certain number of points to the player's defense. ). I also added the currently unused ability to enchant the shield or armor or whatever (this currently is just a point system that does nothing but I'm thinking about doing something like giving a shield attack points). The only problem with this is it makes for some messy if statements.

What you could do is make a function that reflects the player's species and one for their class. You might want to start with some base stats (jump\_height = 1 strength = 3 etc.) and then have the species and classes modify them (for an elf add 2 to the jump\_height). I'm not that great with graphics but I would expect them to work on the same principle.

Hope this helps!

---
Tags: c++, game-design
---


title: Spritebatch not working in winforms

text:
# Question
Title: Spritebatch not working in winforms
I'm using the Winforms sample on the app hub and everything is working fine except my spritebatch won't draw anything unless I call Invalidate in the Draw method. I have this in my initialize method:

```
Application.Idle += delegate { Invalidate(); };

```

I used a breakpoint and it is indeed invalidating my program and it is calling my draw method. I get no errors with the spritebatch and all the textures are loaded I just don't see anything on the screen. Here's the code I have:

```
    protected override void Draw()
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        tileSheet.Draw(spriteBatch);
        foreach (Image img in selector)
            img.Draw(spriteBatch);
        spriteBatch.End();
    }

```

But when I do this:

```
    protected override void Draw()
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        tileSheet.Draw(spriteBatch);
        foreach (Image img in selector)
            img.Draw(spriteBatch);
        spriteBatch.End();
        Invalidate();
    }

```

then all of a sudden the drawing starts to work! but the problem is that it freezes everything else and only that control gets updated. What can I do to fix this? It's really frustrating.

# Answer
To get continuous updates without degrading the UI performance, you'll need the following trick to hook into the windows message queue:

```
public static class NativeMethods
{
    [StructLayout(LayoutKind.Sequential)]
    public struct Message
    {
        public IntPtr hWnd;
        public UInt32 msg;
        public IntPtr wParam;
        public IntPtr lParam;
        public UInt32 time;
        public Point p;
    }

    [SuppressUnmanagedCodeSecurity] // We won't use this maliciously
    [DllImport("User32.dll", CharSet = CharSet.Auto)]
    public static extern bool PeekMessage(out Message msg, IntPtr hWnd, uint messageFilterMin, uint messageFilterMax, uint flags);
}

```

The usage is like so (for bonus points I've added my fixed time step code):

```
    // Hook up idle event (in Form load or wherever)
    Application.Idle += delegate { Application_Idle(); };

    void Application_Idle(object sender, EventArgs e)
    {
        while (AppStillIdle())
            Tick(); // This contains your Update() and Draw() loop
    }

    // Check if any messages are waiting on the queue
    // We only want to keep ticking whilst there are none.
    private bool AppStillIdle()
    {
        NativeMethods.Message msg;
        return !NativeMethods.PeekMessage(out msg, Handle, 0, 0, 0);
    }

    // Tick function handles the fixed timestep and Update/Draw
    const float TARGET_ELAPSED_TIME = 0.0166667f;
    float elapsedSum = 0.0f;
    private void Tick()
    {
        float elapsed = (float)timer.Elapsed.TotalSeconds;
        timer.Reset();
        timer.Start();

        elapsedSum += elapsed;
        if (elapsedSum >= TARGET_ELAPSED_TIME)
        {
            // Game update and draw
            Update(TARGET_ELAPSED_TIME);
            Draw();

            // INVALIDATE GRAPHICS DEVICE CONTROLS
            gdcLevel.Invalidate();

            elapsedSum %= TARGET_ELAPSED_TIME;
        }
        // Return control to UI thread in case more messages arrive
        System.Threading.Thread.Sleep(0);
    }

```

My implementation is based on Tom Miller's blog post: http://blogs.msdn.com/b/tmiller/archive/2005/05/05/415008.aspx

Also floAr's answer references Shawn's blog which contains pretty much the same code :http://blogs.msdn.com/b/shawnhar/archive/2010/12/06/when-winforms-met-game-loop.aspx
> 1 votes

# Answer
There is a very good post by Shawn Hargreaves about XNA with WinForms you should definitly check it out.

In addition here are two tutorials aout XNA in WinForms and WPF, with a bit more complex event handling (both are in german)

Maybe try to set up a timer and rebuild XNAs fixed time step. This will queue the timer in your UI thread processing and update the drawing. Invalidate will be called whenever a new frame is prepared and ready.

```
timer = new Timer();
    timer.Interval = (int)TargetElapsedTime.TotalMilliseconds;
    timer.Tick += Tick;
    timer.Start();

    Stopwatch stopWatch = Stopwatch.StartNew();

    readonly TimeSpan TargetElapsedTime = TimeSpan.FromTicks(TimeSpan.TicksPerSecond / 60);
    readonly TimeSpan MaxElapsedTime = TimeSpan.FromTicks(TimeSpan.TicksPerSecond / 10);

    TimeSpan accumulatedTime;
    TimeSpan lastTime;

    void Tick(object sender, EventArgs e)
    {
        TimeSpan currentTime = stopWatch.Elapsed;
        TimeSpan elapsedTime = currentTime - lastTime;
        lastTime = currentTime;

        if (elapsedTime > MaxElapsedTime)
        {
            elapsedTime = MaxElapsedTime;
        }

        accumulatedTime += elapsedTime;

        bool updated = false;

        while (accumulatedTime >= TargetElapsedTime)
        {
            Update();
            Draw();

            accumulatedTime -= TargetElapsedTime;
            updated = true;
        }

        if (updated)
        {
            Invalidate();
        }
    }

```

I hope this gets you startet!
> 0 votes

---
Tags: xna, c#, spritebatch, windows-forms
---


title: Does Unity 3d cost money?

text:
# Question
Title: Does Unity 3d cost money?
So I installed an Unity engine and I want to develop games by that. I heard that it costs 1500$ to program the code and post the game. Is that true? Did some1 developed a game with it and uploaded it to the Play Store?

# Answer
No, that's not true. It does cost that much for full professional access, but you can program and sell a game with the base free feature-set: License comparison
> 2 votes

---
Tags: unity
---


title: PointSprite in DirectX9

text:
# Question
Title: PointSprite in DirectX9
I was trying to implement a particle system using PointSprites. Draw calls return D3D\_OK but I don't see any particle on the screen. I'm not using Vertex Buffer for the particles, but I use two vectors of vertices and I call the DrawPrimitiveUP function. This is my code:

```
            CreatePntVertices();

            pD3DD -> SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
            pD3DD -> SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
            pD3DD -> SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);

            pD3DD -> SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
            pD3DD -> SetRenderState(D3DRS_ZENABLE, FALSE);

            pD3DD -> SetRenderState(D3DRS_LIGHTING, FALSE);

            pD3DD -> SetFVF(FVF_PNTVERTEX);
            pD3DD -> SetTexture(0, pTex[TEX_POINT]);

            pD3DD -> SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
            pD3DD -> SetRenderState(D3DRS_POINTSCALEENABLE, TRUE);

            pD3DD -> SetRenderState(D3DRS_POINTSCALE_A, 0.0f);
            pD3DD -> SetRenderState(D3DRS_POINTSCALE_B, 0.0f);
            pD3DD -> SetRenderState(D3DRS_POINTSCALE_C, 1.0f);

            pD3DD -> SetRenderState(D3DRS_POINTSIZE, 20.0f);
            pD3DD -> SetRenderState(D3DRS_POINTSIZE_MIN, 3.0f);
            pD3DD -> SetRenderState(D3DRS_POINTSIZE_MAX, 50.0f);

            D3DXMatrixIdentity(&mWorld);
            pD3DD -> SetTransform(D3DTS_WORLD, &mWorld);

            pD3DD -> DrawPrimitiveUP(D3DPT_POINTLIST, pntPlanets.size(), (PVOID)pntPlanets.data(), sizeof(PNTVERTEX));

            pD3DD -> SetRenderState(D3DRS_POINTSIZE, 40.0f);
            pD3DD -> SetRenderState(D3DRS_POINTSIZE_MIN, 9.0f);
            pD3DD -> SetRenderState(D3DRS_POINTSIZE_MAX, 70.0f);

            pD3DD -> DrawPrimitiveUP(D3DPT_POINTLIST, pntStars.size(), (PVOID)pntStars.data(), sizeof(PNTVERTEX));

            pD3DD -> SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);

            pD3DD -> SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
            pD3DD -> SetRenderState(D3DRS_POINTSPRITEENABLE, FALSE);
            pD3DD -> SetRenderState(D3DRS_POINTSCALEENABLE, FALSE);

```

`CreatePntVertices()` is a function that set the position of objects and their color into two vectors of `PNTVERTEX` (`pntStars` and `pntPlanets`). `pTex` is an array of textures. `mWorld` is a `D3DXMATRIX`. `pD3DD` is the Device. `FVF_PNTVERTEX` is set as `(D3DFVF_XYZ | D3DFVF_DIFFUSE)`. I really don't know why it doesn't work, I tried everything to make it work. Maybe, should I use a dynamic vertex buffer instead?

# Answer
> 0 votes
I found out the source of the problem. After days and days, I understood (at last) that with `SetRenderState` (in DirectX9), `float`s have to be converted into `DWORD`s in this way:

```
*((DWORD*)&f)

```

where `f` is the floating point. I already used this method for fog, but I forgot it and it took me other weeks to learn it again. I hope this answer will help other guys with the same problem!

---
Tags: c++, directx, directx9, particles
---


# Question
Title: In OpenGL what's quicker, lots of smaller VAOs, or one large one updated each frame?
In my game engine, a mesh can be made of many submeshes. These submeshes may or may not share vertex data with the rest of the mesh, if they don't they have their own vertex data array.

I've noticed that rendering a mesh with many submeshes that don't share vertices is incredibly slow. This is because each submesh has it's own VAO (and vertex/index VBO pair).

The alternative is to gather the vertices and indices into one pair of VBOs and update them every frame. But will this be much faster?

Is it faster to create one large VAO and update it every frame, or to render many small ones which don't need updating each frame?

# Answer
> 10 votes
I haven't done any benchmarking to compare but there's a relatively unknown feature introduced to core in 4.3 that might be of interest to you. `glVertexAttribPointer` has somewhat silently been deprecated in favor of a new suite of functions:

In 4.4 there's also a compound version of the latter function, `glBindVertexBuffers`, that does N consecutive binds at once (not necessarily consecutive vertex attribute locations!) to save you the call overhead.

In the common use case of drawing a lot of objects with the same vertex attributes but different buffers, this vastly simplifies the work you have to do (and potentially is faster!) Instead of keeping around a VAO for each object, you only need one for each different combination of vertex attributes.

Sample code is worth 1000 words, so here goes.

```
void buildVAO() {
    glBindVertexArray(vao);

    // layout(location = 0) in vec3 position;
    glEnableVertexAttribArray(0);
    glVertexAttribFormat(0, 3, GL_FLOAT, false, 0);
    glVertexAttribBinding(0, 0); // bind to first vertex buffer

    // layout(location = 2) in vec3 normal;
    glEnableVertexAttribArray(2);
    glVertexAttribFormat(2, 3, GL_FLOAT, false, 0);
    glVertexAttribBinding(2, 1); // bind to second vertex buffer

    glBindVertexArray(0);
}

```

The biggest difference you should notice here is that you no longer need a buffer bound to specify your vertex attributes. Hooray for decoupling!

```
struct Object {
    GLuint buffers[2]; // first provides position, second provides normal
    size_t offsets[2]; // beginning of vertex data in buffer
    size_t strides[2]; // stride of entire element in buffer

    unsigned int triangles;
};

void draw(unsigned int count, const struct Object *objects) {
    glBindVertexArray(vao);

    for(int i = 0; i < count; ++i) {
        // consecutive vertex buffer binding points are used here
        glBindVertexBuffers(0, 2, objects[i].buffers, objects[i].offsets, objects[i].strides);
        glDrawArrays(GL_TRIANGLES, 0, objects[i].triangles*3);
    }

    glBindVertexArray(0);
}

```

Here you can see why vertex buffer binding points are useful. Even though they don't contribute to consecutive vertex attribute locations, we can still bind consecutive buffers into those locations.

One last thing to note: if you have a GPU that supports OpenGL 4.5 there *is* a DSA equivalent for each of these functions.

# Answer
> 2 votes
The other answers here are good (maybe better) but I wanted to add my 2 cents.

One approach is for objects that have static verts to all share one VBO. Just pile on the data from each objects into one huge array and make it a VBO. Track offsets and sizes for each object within the VBO and then draw each individual one like this:

```
glDrawElements(GL_TRIANGLES, models[thisItem->model].indSize, GL_UNSIGNED_INT, (void *) (models[thisItem->model].indOffset * sizeof(GLuint)));

```

The issue there then becomes too many draw calls. But depending on your game it might not matter. I've done many successful projects this way with 60fps on the iPhone. But again these are all objects that have static verts that are not changing per frame.

For objects that DO change per frame, like a waving flag, I update the data each frame and draw without a VBO.

```
glVertexAttribPointer(glPrograms[currentProgram].glAttributes[A_vec3_vertexPosition], 3, GL_FLOAT, GL_FALSE, sizeof(FlagVertex), &testFlag.m_Vertices[0].pos.x);
glEnableVertexAttribArray(glPrograms[currentProgram].glAttributes[A_vec3_vertexPosition]);

glVertexAttribPointer(glPrograms[currentProgram].glAttributes[A_vec2_vertexTexCoord0], 2, GL_FLOAT, GL_FALSE, sizeof(FlagVertex), &testFlag.m_Vertices[0].texCoords.x);
glEnableVertexAttribArray(glPrograms[currentProgram].glAttributes[A_vec2_vertexTexCoord0]);

glDrawElements(GL_TRIANGLES, testFlag.m_NumIndices, GL_UNSIGNED_INT, testFlag.m_Indices);

```

For 2d sprites or fonts I used to draw each quad in it's own transform/draw call and got good results because I was sharing a VBO and not having to rebind textures. But another probably better approach is to combine multiple objects in a single mesh but take care of the offset math on the verts in the array instead of doing 1000 transforms. Then you can combine 1000 draw calls into one.

The approach you finally pick really has to do with your situation. And probably is a mix of techniques based on a set of priorities:

* Reduce draw calls as much as possible by combining objects
* combine objects into less VBOs
* batch items that share materials to reduce texture bindings
* avoid dynamic objects/arryas when you can

But 1 and 4 are opposites. Because combining moving objects means having dynamic arrays. So which guideline to give priority to can often only be decided on with testing.

# Answer
> 1 votes
Merge materials to use a single material per object as much as possible. Even sharing materials between objects if possible (eg: 1 leaf material, 1 ground material).

You should batch up materials & VBOs to avoid state changes between opaque render calls.

And you should not need to update most VBOs on every frames, the goal of VBOs is to leave the data on the GPU avoiding expensive bus transfers.

With vertex shaders you can do skinning entirely on the GPU avoiding VBO updates.

To limit data transfers for particles you can use 2 VBOs: one with the vertex values that change on every frame (position, alpha) and one with static values (uvs, color) that is if you cannot use geometry shaders to do point sprite expansion.

There are many web pages explaining best VBO & render practices.

( https://developer.apple.com/library/ios/documentation/3DDrawing/Conceptual/OpenGLES\_ProgrammingGuide/TechniquesforWorkingwithVertexData/TechniquesforWorkingwithVertexData.html )

---
Tags: opengl, performance
---


# Question
Title: What is the difference between an orthographic and oblique projection?
They both seem to be a parallel projection. I know that the angles of axes of viewing differ based on the type of orthographic projection (eg, an isometric projection has equal angles for all the axes).

But what sets the oblique projection apart from the orthographical projection?

I found this image on Wikipedia and I don't see what sets the two oblique examples apart from the dimetric example.

# Answer
> 8 votes
They're both similar, in that they are both parallel projections (lines that are parallel in the source are parallel in the projection). In a parallel projection of `(x, y, z)` onto the `xy` plane becomes `(x + az, y + bz, 0)`. When `a` and `b` are equal, the projection is orthographic; otherwise the projection is oblique.

Another way to look at it is that in an orthographic projection, the projector lines intersect the plane being projected on to at a perpendicular angle (thus, they are *orthogonal*, thus the name of the projection), whereas in an oblique projection those lines form oblique angles (non-right angles) with the projection plane.

# Answer
> 3 votes
I would comment on Josh's accepted answer, which is certainly correct, but you need 50 rep to do that and I just happened to see this on the "Hot Network Questions" sidebar. But I digress...

Coming from a background in geography, there's an easy example of orthogonal vs oblique projections in remote sensing data (like the aerial imagery you see on Google or Bing Maps). Note the rooflines most especially in the following images.

Orthagonal imagery is usually shot from a plane (or satellite) with a camera pointing directly out the bottom of the plane and looks directly down on the ground below. Thus, assuming the aircraft is flying level and the ground is flat, you can take Josh's statement about projector lines intersecting the plane perpendicularly and make the plane the ground and the projector source the camera.

---

Oblique projection imagery is captured at an angle and once properly georeferenced, can provide imagery that can be measured and is generally a bit more "natural" in appearance (in Bing Maps they call this "Bird's Eye"). Again, the projector lines (extending out from the camera) hit the plane at an oblique angle, thus it is an oblique projection.

I know this may not help you actually code a game, but hopefully the photos help give you a better sense of the math involved!

(Image sources: http://www.eagleview.com/Products/ImageSolutionsAnalytics/PictometryImagery.aspx \- I don't have any affiliation with them, this page was just a good reference to pull examples from)

---
Tags: mathematics, projection
---


# Question
Title: Can I use unlicensed art to develop and raise money for my game?
I've been developing a prototype for a game that has been made with art that I have neither paid for or asked for permission to use. Naturally once I move towards selling or distributing my ad-supported game, I'll need to replace the art with its licensed equivalent, or pay for my own.

This is generally how game engines work, with you using an unlicensed copy until you release and start to make money off of it, so I thought maybe it would be the same in the game art world.

Can I legally develop and say, start a kickstarter, using a game with unlicensed art?

# Answer
> 1 votes
To perform any revenue-generating activity with content that you do not have permission to use in that way is going to invite trouble.

I'd recommend asking for permission, creating your own content, or seeking out content with permissive licenses (like things you can find on opengameart.org )

In general, if you can add "(or stolen)" as a synonym for anything you're doing, as you did in your question heading, it's a good sign that it's sketchy and not something you should be doing as a responsible creator.

---
Tags: art, licensing
---


# Question
Title: How can I implement input handling into my game?
I'm making a libgdx game where the player dodges falling objects. To move the player I have it set so that on desktop he moves left and right when you press A and D respectively. I am trying to implement three different methods for the android version:

1. The player puts their finger on the screen and drags the character left and right.
2. The screen is split into two vertical halves and each half acts as a 'move left' or 'move right' directional button. So if you pressed the left half, the character would move left and if you pressed the right half, the character would move to the right.
3. Use the accelerometer to move the character.

I would prefer to implement method 2 but I would use method 1 if I can't get method 2 to work. Method 3 is just a bonus.

So far during my experimenting, the problem for method 1 has been that the character doesn't follow my finger exactly as it is on the screen. The problem for method 2 has been that I can't figure out how to get it to work. Likewise with method 3.

I would very much appreciate it if anyone could point out where I'm going wrong and/or suggest how to fix it.

Here are my relevant classes (sorry about all the commented out stuff, that's just *some* of my experimental code):

```
public class Player extends Entity {

OrthographicCamera camera;
Rectangle rectangle;
Vector3 touchPos;

MoveHelper moveHelper;

public Player(Vector2 pos, Vector2 direction) {
    super(TextureManager.PLAYER, pos, direction);
    rectangle = new Rectangle(); //for hitbox

    moveHelper = new MoveHelper();

}

@Override
public void update() {

    camera = new OrthographicCamera(240, 400);
    camera.position.set(240 / 2, 400 / 2, 0);
    rectangle.set(pos.x, pos.y + 40, 32, 22); //hitbox
    touchPos = new Vector3();
    moveHelper.left.set(0, 40, 120, 360);
    moveHelper.right.set(121, 40, 119, 360);

    pos.add(direction);{

    //if (Gdx.input.isPeripheralAvailable(Peripheral.Accelerometer)) [method 3]
        //float accelX = Gdx.input.getAccelerometerX();
        //pos.x = Gdx.input.getAccelerometerX();
        //camera.unproject(touchPos);

    if (Gdx.input.isTouched()){ //[method 2 below]
        touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
        camera.unproject(touchPos);
            if (moveHelper.left.contains(touchPos.x, touchPos.y)){
                setDirection(-300, 0);}
            else if (moveHelper.right.contains(touchPos.x, touchPos.y)){
                setDirection(300, 0);}
            else
                setDirection(0, 0);

        //[dragging method 1 below]
        touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
        camera.unproject(touchPos);
        pos.x = touchPos.x;// - 16;//240 / 2 - 32;

        //if (touchPos.x > Gdx.input.getX() && touchPos.x < Gdx.input.getX()){// + sprite.getWidth()) {
          //  if (touchPos.y > Gdx.input.getY() && touchPos.y < Gdx.input.getY()){// + sprite.getHeight()) {
            //  pos.x = touchPos.x;}}
    //}

    if(Gdx.input.isKeyPressed(Keys.A)) // left
        setDirection(-300, 0);
    else if(Gdx.input.isKeyPressed(Keys.D)) // right
        setDirection(300, 0);
    else
        setDirection(0, 0);}

    // make sure player stays inside stage
    if (pos.x < 0) pos.x = 0;
    else if (pos.x > 240 - 32) pos.x = 240 - 32;

}
}
}

```

My feeble attempt at making an input helper class:

```
public class MoveHelper {

public Rectangle left;
public Rectangle right;

public MoveHelper() {

    left = new Rectangle ();
    right = new Rectangle ();
}

//public void update() {
    //left.set(0, 40, 120, 360);
    //right.set(121, 40, 119, 360);
//}
}

```

My entity class which is extended by player:

```
public abstract class Entity {

protected Texture texture;
protected Vector2 pos, direction;

public Entity(Texture texture, Vector2 pos, Vector2 direction) {
    this.texture = texture;
    this.pos = pos;
    this.direction = direction;
}

public abstract void update();

public void render(SpriteBatch sb) {
    sb.draw(texture,  pos.x,  pos.y);
}

public Vector2 getPosition() {
    return pos;
}

public Rectangle getBounds() {
    return new Rectangle(pos.x, pos.y, texture.getWidth(), texture.getHeight());
}

public void setDirection(float x, float y) {
    direction.set(x, y);
    direction.scl(Gdx.graphics.getDeltaTime());
}

}

```

My entitymanager class:

```
public class EntityManager {

private final Array<Entity> entities = new Array<Entity>();
private final Player player;

public EntityManager(int amount) {
    player = new Player(new Vector2(110, 15), new Vector2(0, 35));
    for (int i = 0; i < amount; i++) {
        float x = MathUtils.random(0, ManicMeltdowns.WIDTH - TextureManager.DROPS.getWidth());
        float y = MathUtils.random(ManicMeltdowns.HEIGHT, ManicMeltdowns.HEIGHT * 3);
        //float speed = MathUtils.random(2, 5);
        float speed = 2;
        addEntity(new Drops(new Vector2 (x, y), new Vector2(0, -speed)));
    }
}

public void update() {
    for (Entity e : entities)
        e.update();
    player.update();
    //checkCollisions();
}

public void render(SpriteBatch sb) {
    for (Entity e : entities)
        e.render(sb);
    player.render(sb);

}

private void checkCollisions() {
    for (Drops e : getDrops()) {
        if (e.getBounds().overlaps(player.rectangle)) {
        //(e.getBounds().overlaps(player.getBounds())) {
            ScreenManager.setScreen(new GameOverScreen());
        }
    }
}

public void addEntity(Entity entity) {
    entities.add(entity);
}

private Array<Drops> getDrops() {
    Array<Drops> ret = new Array<Drops>();
    for (Entity e : entities)
        if (e instanceof Drops)
            ret.add((Drops)e);
    return ret;
}
}

```

All of this is finally output in my gamescreen simply as "entityManager.update();" and "entityManager.render(sb);"

I know my code is **terrible** but any help would be great. Many thanks!

# Answer
On LibGDX you have a so called InputProcessor

```
public class MyInputProcessor implements InputProcessor {
   @Override
   public boolean keyDown (int keycode) {
      return false;
   }

   @Override
   public boolean keyUp (int keycode) {
      return false;
   }

   @Override
   public boolean keyTyped (char character) {
      return false;
   }

   @Override
   public boolean touchDown (int x, int y, int pointer, int button) {
      return false;
   }

   @Override
   public boolean touchUp (int x, int y, int pointer, int button) {
      return false;
   }

   @Override
   public boolean touchDragged (int x, int y, int pointer) {
      return false;
   }

   @Override
   public boolean mouseMoved (int x, int y) {
      return false;
   }

   @Override
   public boolean scrolled (int amount) {
      return false;
   }
}

```

Here is an example
> 1 votes

---
Tags: java, libgdx, movement, input
---