title: Error in plane transformation

text:
# Question
Title: Error in plane transformation
I have a bunch of coplanar points, who sit on plane `P`. I want to translate the plane to `Q` with the points upon. Here is what I do:

I take three points from `P`, say `a`, `b`, `c`. Their centroid is denoted by `c(a,b,c)`.

I pick the local origin as `O = c(a,b,c)` and local `XYZ` as:

```
x = normalize(Oa);
v = normalize(Ob);
z = x.crossProduct(v);
y = x.crossProduct(z);

```

I apply the same method to their global coordinates on `Q`, which are `d`, `e`, `f`.

```
O_ = c(d,e,f);
x_ = normalize(Od);
v_ = normalize(Oe);
z_ = x_.crossProduct(v_);
y_ = x_.crossproduct(z_);

```

Then, I use the transformation matrix as follows:

```
Matrix input = [x,y,z];
Matrix output = [x_,y_,z_];
Matrix T = output.multiply(input.transpose());

```

After this step, I multiply the coordinates of a point `p` that sit in plane `P` with matrix `T`. Of course, before that, I take the vector difference `p - O`.
The result should be the transformed point minus target origin (`q - O_`).

Hence, for each `p` in `P`, I transform `p` to its place in `Q`, which is denoted by `q` using the following computation:

```
q = T.multiply(p.subtract(O)).add(O_);

```

But what I get is, the reflection of the points through an imaginary (I don't know which) axis.

Am I missing some step? Is there a wrong computation?

# Answer
> 1 votes
I don't know if this is a typo in your question or the actual mistake:

```
x = normalize(Oa);
v = normalize(Ob);
z = a.crossProduct(b);
y = x.crossProduct(z);

```

For one you don't seem to be using `v` at all, but your `z` looks wrong to me. Did you mean the following?

```
z = normalize(Oa.crossProduct(Ob));

```

Note the `Oa` and `Ob` instead of `a` and `b`. The difference is the preserved perpendicularity of z on the plane `P` if `P` is moved away from the origin. I guess you wanted to do that through `p.subtract(O)` but that doesn't suffice.

Also note that I normalized `z`. This will result in orthonormal XYZ on both planes `P` and `Q` and means that scale is preserved. If the triangles `abc` and `def` are not similar (i.e. one is stretched) then `T(P) = Q` but `T(a) != d`. Don't normalize anything if you want to preserve stretching.

---
Tags: rotation, geometry, transformation
---


title: Kryonet usage for game networking

text:
# Question
Title: Kryonet usage for game networking
Im making a game where real-time data is exchanged between server and clients, and I was using java UDP sockets straight up, but I reached a point where I actually need to know if a few specific packets do arrive or not, like RemoveObject, ChangeLevel etc. UDP alone isnt enough, I needed some reliability.

So i tried to implement a thin layer on top of UDP by following this great article: http://gafferongames.com/networking-for-game-programmers/

Still, although it's being great to learn low-level networking, its also very hard and I've grown tired, so i looked up for a good alternative and found Kryonet.

Kryonet is said to handle both UDP and TCP requests at the same time, by using two ports (although apparently a single port for both protocols can be used...).

My initial idea (which seems more logical for me) would be to send via UDP the packets with info about object state updates and other real-time dependent information, whilst using TCP for object creation, removal, state-changes or even eventually chat-messages.

Still, every example i saw until now only uses TCP even for real time games, which i find odd when every article i read about game networking strongly discourages such.

I also do not understand how UDP and TCP work at the same time since the article states:

> The problem is that since TCP and UDP are both built on top of IP, the underlying packets sent by each protocol will affect each other. Exactly how they affect each other is quite complicated and relates to how TCP performs reliability and flow control, but fundamentally you should remember that TCP tends to induce packet loss in UDP packets.

Please explain how is Kryonet supposed to be used on game networking and why it should be used in such way regarding common knowledge about both protocols.

# Answer
**Summary of TCP and UDP**

* UDP: Sends packets as fast as it can and never checks whether or not the packet has been received. Order is not important either.
* TCP: Packets will be verified and an acknowledge must be received by the endpoint. Packet order matters.

**Answer**

Yes, it was discouraged to use TCP in the past for real-time games. It still is, to a certain extend, but for many reasons, TCP is acceptable:

* TCP guarantees the packets will be received by the endpoint. This will **limit the bugs in the information transmitted**.
* TCP might be slower overall, but with the current speed of the Internet network, **the difference is not significant for small games**. The data should be transmitted and received almost at the same rate as UDP by now.

TCP still has some downsides:

* TCP **can be slow if the ping is high**. TCP always waits for an answer to a packet and if the ping is high, the time between packets can become a problem.
* Depending on the routers and the networking libraries, TCP **can apply some optimization that can annoy the programmer**, Ex: Packet grouping. Some routers and libraries wait for a certain amount of TCP packets and group them before sending them. This can become a real problem in real-time games as you want your packet to be sent as soon as it is ready.

Both TCP and UDP can run just fine together on a computer, **as long as both run on different ports**. If you try to send TCP and UDP packets on the same port, then you will have problems like the one you quoted.

Regarding how you should use them in a game, it is up to you in the end, but here are some guidelines:

* TCP: **Important packets than must be received** by the server or client in the right order, like character creation, sending the map or the enemy data, etc.
* UDP: **Fast, real-time information** that can be missed some frames without affecting the game too much, like player position, animations, score, etc.

Personnaly, I would tell you to start with TCP and if you have problems with it, you can implement UDP. But, as I said, with the current speed and reliability of the Internet network, you should have no problem at all with either.

**EDIT**: As far as I can see, Kryonet looks like a pretty standard networking library. You can also google "game networking tutorial" to get a more general idea.
> 5 votes

# Answer
I am using KryoNet for a Java game i am making. I will sometimes have several hundrets of units at the same time. My approach has been to send frequent unit updates in small UDP packages and use interpolation on the client. I also rarely send larger unit update packes, also via UDP, with information that does not need to update as frequently as position and rotation. I then use TCP for important packages that i need to make sure get there.

If i try to send all my unit packages via TCP, the network can't handle it and i get an exception. So UDP is great for sending a lot of not-that-important packages.
> 3 votes

---
Tags: networking, udp
---


# Question
Title: 2D terrain with midpoint displacement and collision
I followed this theory Here to implement a simple scrolling 2D terrain for my running game. I am used to dealing with collision via a tile system but am looking for a good theory on how to perform terrain collision (keeping the player on-top the land) with a midpoint displacement 2D terrain

I am not worried about the physics aspect but how to determine if a character intersects an array of points generated by the theory above. Example if I have an array of points

```
Points[]

```

these points are used to draw lines to make a terrain. Now in my mind I would first find the player center. Take the center X and see which two points it is between. So if X is 4.6 lets say it is between points that lay on X=3 and X=6.

```
Player X = 4.6
Point1 X = 3, Y = 3
Point2 X = 6, Y = 5

```

So now knowing this I somehow need to calculate what Y would be giving that X = 4.6. And once I have Y ensure that the Player Y \> CalculatedY. If it is not push the player up to what Y the player should be.

So I guess what I a saying is

```
X = 3, Y = 3
X = 6, Y = 5
X = 4.6, Solve for Y

```

# Answer
I will assume that the player collides with the ground only on the middle point.

We can do an approximation of the height of the terrain at a given point with this:

```
double x = 4.6;
double relativeX = x / widthBetweenPoints;
int terrainIndex = Math.floor(x);
double ratio = relativeX - terrainIndex;
int y = Points[terrainIndex] * (1 - ratio) + Points[terrainIndex + 1] * ratio;

```

Where

> x is the x position of the Player, in pixels.
>
> relativeX is the position of the player scaled down to the array, so that we know on which cell of the array he stands.
>
> widthBetweenPoints is the width, in pixels, between the array points.
>
> terrainIndex is the cell the player is standing on (1 in this case). In fact, the player stands between cell 1 and 2, but we round down to 1.
>
> ratio is where the player stands between the two points (here, 1 and 2, and the ratio is 30%)
>
> Points\[\] is the array containing the y values of the points or the terrain.

More in details:

1. We start by scaling the x value of the player down to the size of the terrain. If the x value of the player is 4.6 and the width between 2 points of the terrain is 2, then the relative position is 1.3. The player between point 1 and 2 of the terrain (with index starting at 0) and is at 70% towards 1 and 30% towards 2. More visual: 1 - - P - - - - - - 2
2. Then, we extract the current terrain index by getting the integer part of the relative x value and extract the ratio of "in between" by getting the floating part.
3. We then multiply the y value of the terrain at cell 1 by 70% and the value of cell 2 by 30%.

Just watch out that terrainIndex + 1 does not go out of bounds of the array.

Then you can apply as much physics or collisions as you want.
> 1 votes

---
Tags: xna, collision-detection, monogame, terrain
---


title: 2D Side Scroller Game Without A TileMap

text:
# Question
Title: 2D Side Scroller Game Without A TileMap
I want to create a 2D side scrolling game in a similar style as the game "Castle Crashers". (Go to: http://store.steampowered.com/app/204360/ to see some pics of the game).

I have experience creating 2D games which use an array of tiles (a tilemap), to see if the player/enemies/bullets are moving to a blocked or unblocked tile by referencing the entities x and y coordinates with the tile in the corresponding location.

My question is: How do I implement collision with the "game map", in a game that doesn't use tiles, but instead shapes.

For instance: if the current "map" was a circle, the p\[layer could move freely around the inside of the circle, but could not leave the circle.

Sorry if this question is long-winded and confusing, but I would really appreciate some help with this!

Thanks!

# Answer
I'm assuming you're either using some sort of entity-component system, or else you have in-game classes that represent your objects.

Either way, you have some reference to your in-game objects (players, walls, enemies, etc.) At a minimum, these objects should have:

* A position
* A sprite (display)
* A collision primitive (axis-aligned bounding box?)

All you need to do, then, for collisions, is check the collision primitives against each other. (Mentally, you can imagine this box that moves when your player/objects move.)

Of course, this solution has O(n^2) complexity (check every primitive against every other primitive), so you may need to use something like a quadtree for performance (to limit which objects are checked -- only against near neighbors).
> 2 votes

# Answer
You can use a raycasting (or linecasting) based collision detection system. At a very high level, you cast rays from your player (preferably from the edges of it's collider box) into the game map. When the ray hits something, you can check to see what its hit, and if it's a collidable surface, resolve the collision and adjust player movement as appropriate. This method is pretty agnostic to how your game map is built (tilemap, models, geometric shapes, etc).

For more technical details, you can view my own question on a similar topic. While the code presented is C# (and for Unity), you could easily adapt it for any language.

Here's an image to help visualize the system

Some resources:
> 1 votes

# Answer
Simply use shapes and AABB collisions.

Keep a tiled map. Create an approximation of a circle using tiles and create a rectangle for each of the unwalkable tiles.

Next, when you create a player or any movable entity, simply create a Rectangle around them too. Before moving, look whether or not the player's rectangle would collide with any of the wall's rectangle and allow the movement accordingly.

Here are some resources to read about AABB collisions:

https://stackoverflow.com/questions/22512319/what-is-aabb-collision-detection

http://www.gamedev.net/page/resources/\_/technical/game-programming/swept-aabb-collision-detection-and-response-r3084

http://www.gamefromscratch.com/post/2012/11/26/GameDev-math-recipes-Collision-detection-using-an-axis-aligned-bounding-box.aspx
> 1 votes

---
Tags: java, 2d, maps, side-scroller
---


# Question
Title: Issues using real names in a soccer player game
Is illegal to use the real player and team names in a game? When I say game could be and desktop, mobile or fantasy game.

If is illegal, is ok to change a little bit names? Instead of using Messi could I use Messsi (or something similar)?

All gambling and statistics soccer websites have permissions to use those names?

Thanks!

# Answer
> 2 votes
No, not generally. Not without permission.

Gambling and stats sites are a different case. There's a difference between using someone's name in a factual article about that person and using their name and likeness in a FIFA-like game.

Minor spelling variations are not enough, otherwise we'd all be playing Lorrd of teh Ringz games.

# Answer
> 1 votes
Celebrities have the rights of publicity in their own likeness which means that you're not allowed to make a profit off of something with their name or face without their permission. You could make a game that uses characters that are clearly meant to represent famous athletes (as long as the difference is enough to protected under the fair use policy and it's not simply a caricature).

I would strongly suggest that if you make a game, you should use all of your own original content because it's much better to make a less popular game than to be sued by your favorite soccer players.

---
Tags: legal
---


# Question
Title: What is the best methodology in mounting customizables to a 3d avatar in Unity?
Someone I know suggested just making every customizable on the model then just hide the non active ones. But that doesn't sound very efficient for me.

So my question is what is the best method to use for making customizable 3d avatars in general? And specifically what would be best used in Unity3d?

# Answer
> 2 votes
Another programmer friend gave me this which I think is also an answer to the question

http://forum.unity3d.com/threads/16485-quot-stitch-multiple-body-parts-into-one-character-quot

# Answer
> 1 votes
How exactly to make a 3D avatar customizable depends on the exact customizations desired (eg. change color? change clothing? change gender?) For example, changing color could mean swapping the texture used in the model's material. However the question about mounting objects is pretty straightforward...

If the character has a skeleton (and if this is an animated player model, it has a skeleton for the animation) then simply hierarchy link customization objects to specific bones in the character's skeleton. You can easily assign a parent to an object in code.

---
Tags: 3d, unity, methodology
---


# Question
Title: Is SDL2 alone capable of dynamic (or deferred) lighting?
I'm talking about JUST SDL2, not OpenGL or DirectX. Would drawing deferred lighting bulk the CPU up and how would it be done?

# Answer
> 1 votes
SDL2 provides no facilities for computing lighting, so yes, if you don't use shaders through OpenGL, D3D, etc. to do deferred rendering, or rendering a scene of any complexity for that matter, you're going to leave all that embarrassingly parallel and SIMD work to the CPU.

The concept is exactly the same whether you're doing it on the GPU or the CPU. Instead of summing each light's contribution in a loop over the objects, you're summing each object's contribution in a loop over the lights (where much of the object's data is cached using the G-buffer).

What you should get out of this is that **you don't want to do any sort of 3D rendering without hardware acceleration**, which on the PC requires you to use either OpenGL or D3D.

---
Tags: sdl, deferred-rendering
---


# Question
Title: Game code difference between consoles (PS3/PS4) and PC
I'm interested in game development and have some very curious questions. Im a newbie in game dev so pardon my silly mistakes and question and repetition if any. I hope biggies here will guide me and help me. So, here are my questions:

1. PS3 hardware is like low end PC and PC is very high end, still the games on PS3 can still run very nicely at 720p in 30FPS and some of them even in 3D with very high textures like in uncharted series, god of war and other games, while PS3 is not that powerful compared to high end gaming rig. So my question, is this because the game code on PS3 is a direct machine code written on blu ray game disk's, no abstraction layers in PS3? Because, what i know from PC game code, that it has to go though lots of abstraction layers and hence take longer and powerful hardware to completely process game data. While this may not be case with consoles and the game code their is direct machine code.
2. But if PS3 game code is layered code as well just like in PC then can someone please elaborate the layers in a simple block diagram? And explain in short how that code works in consoles (PS3) vs in PC?
3. I guess its a similar question but just being curious. Since, the PS4 configuration is similar to a low or mid end gaming PC, so would there be a difference between game code? And if there is a difference, how much that is?
4. How is an age old hardware can still perform pretty well like in consoles (PS3/PS4/X360/XBONE)?

I am an embedded developer so very familier with programming like C/C++. Also had some experience with core java as well. But, dont know anything about game development. Sorry for being stupid, i hope i am very clear in asking questions and thanks for answering. :)

Ashu

# Answer
1. Usually, the reason that consoles perform better than PCs with equivalent hardware is that the hardware available on a given console is well-defined, and it is possible for programmers to make optimizations that are not possible for PC games, which need to run on a wide range of hardware configurations. AMD's Mantle API for PC boasts the ability to make these optimizations, but only because it works based on certain hardware assumptions (GCN architecture).
2. The biggest difference is that PC code has to go through a very complex operating system, while code for a PS3 goes through a very thin layer that goes right to the hardware. Most of the performance differences come from the high cost of memory allocation on PC and the system resources that background processes use.
3. Most of the game's code would be very similar. The biggest differences would appear in the code associated with file systems, memory management, rendering, and sound because the APIs are different. Even so, the PS4 uses OpenGL and the Xbox One uses D3D, which are both APIs that PC games use, so the code is going to be much more similar than, say, the code between PC and PS3 or Wii/Wii U.
4. See points 1 and 2.
> 2 votes

---
Tags: game-design, software-engineering, cross-platform, console, pc
---


# Question
Title: How to use "weighted average easing" correctly with variable framerate?
I often use a weighted average for smoothly animating numerical values to a target value, like so:

```
frame(dt) {
    value = ((value*someFactor) + targetValue) / (someFactor+1)
}

```

As you can see `dt` (delta time) is not used at all, so the result is not the same for different framerates. How can `dt` be applied correctly here?

# Answer
This formula updates `value` so a constant fraction of the difference from the `value` and the `target` is removed each frame. Let `alpha = 1/(someFactor+1)`. Then we can rewrite updating to the new `value'` as:

```
value' = (1-alpha) * value + alpha * target

```

Then basic algebra says

```
value' - target = (1-alpha) * value + alpha * target - target
value' - target = (1-alpha) * value + (alpha-1) * target
value' - target = (1-alpha) * value - (1-alpha) * target
value' - target = (1-alpha) * (value - target)

```

Let `u` be the difference between value and target, i.e. `u = value - target` and `u' = value' - target`. Thus:

```
u' = (1-alpha) * u

```

Here we have an option; I will pick the one that doesn't involve calculus. We can repeat this process:

```
u'' = (1-alpha) * u' = (1-alpha) (1-alpha) * u

```

We can see the pattern is that after `n` frames, the difference from the target is `(1-alpha)^n * u_initial`. Let's assume that your game runs at some framerate, and you have adjusted it to your liking. Then after `x` seconds, `n = x/dt_nominal` frames will have passed, where `dt_nominal` is the typical dt when you adjusted it (so 16.6ms for 60fps). So now `u` will be `(1-alpha)^(x/dt_nominal) * u_initial`.

The beauty is that this formula is defined for any real `x`, not just ones which make the exponent a natural number. So here we can replace `x=dt` as the duration of a frame, and get `(1-alpha)^(dt/dt_nominal) * u_initial`. But, using some properties of the exponential:

```
(1-alpha)^(dt/dt_nominal) = e^(-dt * ln(1/(1-alpha))/dt_nominal)

```

So now we can write what the difference is after two frames:

```
u'' = exp(-dt2 * ln(1/(1-alpha))/dt_nominial)
    * exp(-dt1 * ln(1/(1-alpha))/dt_nominial) * u_initial
u'' = exp(-(dt1+dt2) * ln(1/(1-alpha))/dt_nominal)

```

Basically, this formula lets us calculate what the value will be at any arbitrary point in the future. We just choose our update rule to calculate the value `dt` seconds in the future. We also got the nice property that our solution is independent of how many frames occur or their duration, because the final value depends only on the sum of the durations, even though we calculate it individually for each frame.

So we can make our update rule:

```
beta = ln(1/(1-alpha))/dt_nominial
     = ln((someFactor+1)/someFactor)/dt_nominial
amount = exp(-dt * beta)
value = (amount) * value + (1-amount)* target

```

Note that `beta` is a constant. You can figure out what `beta` is for your code, and going forward adjust `beta` directly rather than using `someFactor`. It turns out `beta` is related to the half-life: it is the 1/e-life, instead of the 1/2-life.

**BONUS**

If you assume your frame times are all reasonably small and so is `beta`, then a useful approximation is

```
exp(-dt*beta) ~= 1 - dt * beta

```

Thus your update rule is:

```
beta = ln(1/(1-alpha))/dt_nominial
value = (1 - dt * beta) * value + (dt * beta) * target

```

In the inner loop you therefore avoid a transcendental function. In UI code, use `exp`. If you are moving particles, use the approximation.
> 3 votes

# Answer
I'm assuming that you're incrementing `someFactor` every frame, yes?

```
someFactor += 0.1f;

```

Why not try incrementing it based on `dt`?

```
someFactor += 0.1f * dt;

```

This concept is reified in Jason Gregory's *Game Engine Architecture* under Section 7.4. if you're interested in reading into it further.
> 0 votes

---
Tags: mathematics, animation, frame-rate
---


# Question
Title: Is it possible to use an image, sound or font without importing them externally? [SDL2]
It's hard to explain my question, but I will try my best.

When loading sounds, images or fonts in SDL2 (with SDL\_image, SDL\_mixer, SDL\_ttf) you need to load them from an external source path. For example, `res/image.png` \- the issue I have with this is that the user can edit this file which changes the look of the game.

Is there a way in loading the asset internally? (If that's the right term?) So that it cannot be edited by other people.

Thanks.

# Answer
> 0 votes
What you are looking for is what is known as a "pack/package file" or "assets pack", these are just some of the common names. Most medium to large size games adopt this pattern of packing all loose game assets, such as textures and sounds, into a single file. This is done for three main reasons:

1) To save disk space by compressing the package file;

2) To make difficult for hackers to change game content;

3) To speed up loading and copying of files, since a single large file reduces seek time in the media and data fragmentation in the local File System.

A package file is usually a custom file format devised by the game developer, but most of them mimic a simple directory structure of an OS or implement a virtual File System. Some pack files are just ZIP files that you can open with any ZIP file explorer. Many games actually use plain ZIP files.

If security concerns are really high, you could also go to the extreme of encrypting the assets inside the package file. But this would not be very feasible for a game, since it would slow asset loading to a crawl.

Now regarding the SDL integration, if you had your game assets stored inside one ZIP file, for example, then you would open the ZIP and decompress the data in-memory, possibly using a library like miniZ, and then pass the raw decompressed bytes to one of the equivalent memory loading functions of SDL, like `IMG_Load_RW()`.

# Answer
> 0 votes
You can hard code it in your code itself, for example if you import an image from a 2D array you can hard code it, you can do something similar to 3D models and even sound files (1D arrays) (at the lowest level they are all 1's and 0's and as such can be hard coded if they can be represented as 1's and 0's ), be warned through that this is a heavy load on your compiler and does not make for easy coding (by the way why don't you want your users to change things about your graphics?)

---
Tags: game-design, sdl
---


title: SDL2_ttf gradient

text:
# Question
Title: SDL2_ttf gradient
I want to render some text using a gradient instead of a solid color, but I can't figure out how to. I first load a gradient like this:

```
SDL_Surface* gradient = IMG_Load("blue-cian.png");

```

then I render the text I'm using:

```
SDL_Surface* text = TTF_RenderText_Blended(font, "Text", 30);

```

then I want to blit the text to the gradient but only keeping the pixels inside the text not the ones surrounding it to create a texture and render it to the screen. I guess I need to use SDL\_SetSurfaceAlphaMod and/or SDL\_SetSurfaceBlendMode to use only the opaque pixels when blitting the two surfaces. But I don't completely understand how that works and I only get either just a square colored with the gradient:

or a completely transparent square.

This is how it is supposed to look

but I just can't do it, please tell/explain me how to use the rendered text surface as an aplha mask for the gradient.

# Answer
> 1 votes
I've been combing through SDL functions to see if there's anything useful, and I might have found one solution, albeit rather expensive. I'm sure there's a better method out there.

* Create your gradient and text as SDL\_Surfaces.
* Process every pixel of the texture's Surface to determine if it is transparent or not. If it **is** transparent, set its color to some arbitrary color you never intend to use. If the pixel **is not** transparent, set it to be transparent. You should be able to complete this just by using SDL\_GetRGBA and SDL\_MapRGBA.
* Blit your font surface onto your gradient surface. This should give you your desired font, but with an opaque background.
* Again, process every pixel; if the pixel's color is equal to the arbitrary color you set it to earlier, set it to be transparent.

This should hopefully give you exactly what you want, but I have not tried it myself. Check out this post on Stack Overflow to see a similar example.

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


# Question
Title: Is using something like MakeHuman frowned upon while developing 3D games?
I came across this interesting application called MakeHuman, and I was wondering what developers in the gaming community thought about creating and exporting characters to Unity using this application. I'm not an artist, so a tool like this helps me create characters without having to pay someone else to model them from scratch.

If I were taking a class in game development, would it be permissible to use something like this to create characters rather than create them myself (in Blender or Maya, for example)? What benefits are there to consulting an artist rather than using tools like this?

# Answer
Employing an artist would give your game a specific aesthetic that will help it stand out, but it's perfectly acceptable to use whatever tools available to make your game. Usually the assets produced by the more user friendly tools out there look sortof bland. You can usually tell when someone has been using the out-of-the-box assets from Poser, for example.

Unless the class is *about* 3d modelling, the professor isn't going to care how you *make* your assets, as long as you don't steal another game's assets *and* call them your own, or use assets commercially that require a license.

Don't be afraid to dig into Blender, either. While you say you're not an artist, you don't have to have amazing realism right away, or ever. Start by making simple props, and keep looking at tutorials to learn new techniques. Your models don't have to be realistic, they just need to be different. Show us things we've never seen before instead of trying to beat people with more experience at their own game.

And don't make another zombie/survival/simulator game.
> 3 votes

# Answer
The first issue when looking at any tool is legal, do I have the right to use it. MakeHuman allows just about any commercial and noncommercial usage of it's creations so that's fine.

The second issue is if it's a good idea, this depends if you think you can create a better human or more fitting human then you should if you think your humans will not be so great then you probably shouldn't (unless it's a demand by your class).

Lastly remember efficiency the MakeHuman app does not appear to have a polygon slider meaning that it produces humans of one quality only, this can be difficult if you want to generate a large number of humans (to many polygons making them to slow) or if you want to generate movie quality (to few polygons, people will notice).

The advantage of asking an artist rather then using the tools yourself is that hopefully an artist will know better what he/she is doing and will produce better results, usually artists are more skilled with the more complex tools (blender and maya) and can therefor produce better results of course even then they might still not be better then a purpose build app such as MakeHuman.
> 0 votes

---
Tags: assets, education
---


title: Preventing diagonal movement

text:
# Question
Title: Preventing diagonal movement
I was originally fine with diagonal movement but it's clashing with my sprite animation...

```
    public void keyPressed(KeyEvent e){
    int key = e.getKeyCode();

    switch(key){
        case KeyEvent.VK_W:{
            dir = 3;
            velY = -speed;
            break;
        }
        case KeyEvent.VK_S:{
            dir = 2;
            velY = speed;
            break;
        }
        case KeyEvent.VK_A:{
            dir = 1;
            velX = -speed;
            break;
        }
        case KeyEvent.VK_D:{
            dir  = 0;
            velX = speed;
            break;
        }
    }
}

public void keyReleased(KeyEvent e){
    int key = e.getKeyCode();

    switch(key){
        case KeyEvent.VK_W:{
            velY = 0;
            break;
        }
        case KeyEvent.VK_S:{
            velY = 0;
            break;
        }
        case KeyEvent.VK_A:{
            velX = 0;
            break;
        }
        case KeyEvent.VK_D:{
            velX = 0;
            break;
        }
    }
}

    public void update(){
    y += velY;
    x += velX;
}

```

I thought that perhaps a switch statement or an if else statement would prevent multiple keys from firing at once, but it's not working out. I even tried synchronizing some methods but still to no avail. Any suggestions? And please ignore the dir variable I use it to find the direction the player is facing.

# Answer
Obtaining multiple key presses can be found in this answer: How do I handle multiple key presses in Java?

Assign each one to a boolean variable and then check each key and add to the movement vector. Opposite keys will cancel out, and you can also test whether a key is already in use based on that.

```
if(noDiagonal)
{
    velX = 0;
    velY = 0;

    if(keyLeft) velX += -1;
    if(keyRight) velX += 1;

    if(velX == 0)
    {
        if(keyUp) velY += -1;
        if(keyDown) velY += 1;
    }
}
else // In case you change your mind...
{
    velX = 0;
    velY = 0;

    if(keyLeft) velX += -1;
    if(keyRight) velX += 1;
    if(keyUp) velY += -1;
    if(keyDown) velY += 1;

    // Normalize to prevent high speed diagonals
    float length = sqrt((velX * velX ) + (velY * velY ));
    velX = velX/length;
    velY = velY/length;
}
velX *= speed;
velY *= speed;

```

Pick which animation/direction to use based on the speed in that direction, rather than the key. This will make it easier to handle automatic animation later (like in a cutscene), or you can turn that part off individually (like if they're standing on a conveyer belt).
> 3 votes

---
Tags: java, movement
---


# Question
Title: Calculating distance for Gauss Map optimized SAT
There's an optimization method for the separating axis test in 3D that uses *Gauss Maps* to discard certain redundant axes from the set of axes that need to be tested generated by edge-edge cross products.

A detailed presentation can be found here. Along with some source code.

The presentation also states that using the Gauss Map method lets you compute the distance between the two polyhedra along the separating axis orthogonal to corresponding edges (i.e. ones that the Gauss Map method doesn't discard) in O(1).

This is done by considering the plane formed by the cross product of the two corresponding edges fixed on one edge, and finding the minimum distance from a vertex to the plane on the corresponding edge.

My question is:

* Why isn't the distance found this way in the general case when testing the axis formed from the cross product of two edges (i.e. when not using the Gauss Map optimization)?

Generally the method I see used is projection intervals, or fixing the plane for the separating axis to its corresponding edge or face on one polyhedron, and ensuring all vertices of the other polyhedron fall outside.

# Answer
When you take two edges on two polyhedra you don't know if they form a face on the Minkowski difference. Only feature pairs that form a face can be a potential axis of separation. Since this information is unknown you must naively test all edges against all edges.

This means a supporting point must be computed for each cross product axis since it is not known if the two edges in question are supporting or not.

Since testing for Voronoi region overlap (aka Gauss Map arc intersection test) will tell you whether or not the two edges are supporting, support points can be directly computed in constant time by computing the closest points between the two segments.
> 2 votes

---
Tags: mathematics, separating-axis-theorem
---


# Question
Title: Handling early/late/dropped packets for interpolation in a 3D multiplayer game
I'm working on a multiplayer game that for the purposes of this question, is most similar to Team Fortress.

Each network data packet will contain the 3D position of the target moving object. (this object could be another player) The packets are sent on a fixed interval, and linear interpolation will be used to smooth the transition between packets. Under normal circumstances, interpolation will occur between the second-to-last packet, and the last packet received.

The linear interpolation algorithm is the same as this post:

Interpolating positions in a multiplayer game

I have the same issue as in that post, but the answers don't seem like they will work in my situation. Consider the following scenario:

1. Normal packet timing, everything is okay
2. The next expected packet is late. That's okay, we'll just extrapolate based on previous positions
3. The late packet eventually arrives with corrections to our extrapolation. Now what do we do with its information?

The answers on the above post suggest we should just interpolate to this new packet's position, but that would not work at all. If we have already extrapolated past that point in time, moving back would cause rubber-banding.

The issue is similar in the case of an early or dropped packet.

---

So I believe what I am looking for is some way to smoothly deal with new information in an ongoing interpolation/extrapolation process.

Since I might be moving on to quadratic or even cubic interpolation, it would be great if the same solutiuon could be applied to those as well.

# Answer
Latency, the #1 enemy of networked games.

So, your problem is, that you don't know if packet loss happened or packet is late and thus you might receive packet, that should be discarded.

You have to timestamp your packets or use incrementing id that is sent with packet, that helps you to identify packets that should not be cared anymore. If you use id for example, you could check on client, if justArrivedPacketID \> lastPacketId and process it.
> 1 votes

# Answer
I would never extrapolate. It leads to strange artifacts (e.g. a player frozen in place) but it's arguable whether that's worse than extrapolating. Also, when you get the packet, just "teleport" the player.

It's not great, but then again, losing packets sucks.
> 0 votes

---
Tags: multiplayer, interpolation, extrapolation
---


# Question
Title: Why are my Box2D wheels slipping on ground?
I have a car, set up in Box2D as a rectangle connected with two wheels using `WheelJoint`s:

The wheels are defined as follows:

```
    FixtureDef wheelFixtureDef = new FixtureDef();
    wheelFixtureDef.density = 1.f;
    wheelFixtureDef.shape = wheelShape;
    wheelFixtureDef.friction = 0.98f;
    wheelFixtureDef.restitution = 0.3f;

    // wheel joint (only one of the wheels has the motor enabled)
    wheelJointDef.dampingRatio = 0.9f;
    wheelJointDef.frequencyHz = 20.0f;
    wheelJointDef.motorSpeed = 15.4f;
    wheelJointDef.maxMotorTorque = 100.f;

```

And the ground:

```
    FixtureDef groundFixtureDef = new FixtureDef();
    groundFixtureDef.density = 0.f;
    groundFixtureDef.friction = 1.0f;

```

Still, when trying to climb that hill in the picture, the wheels reach a stage where they just keep slipping, and it slides back down.

Why does it slip even though the friction coefficients are set high? How can I make it overcome that hill?

# Answer
> 1 votes
Your car is slipping for the same reason that a car hanging up-side down, riding the ceiling, with 100% friction would slip. 100% friction roughly means that 100% of the force exerted via the wheels on the terrain is used to counter movement perpendicular along the normal of the terrain. But this force still isn't enough to counter the force of gravity. This happens when the forces working up-on the vehicle that direct downwards are larger than those pointing towards the ground. You'll probably see wheel slippage starting from hills with a 45 degree slope.

You could solve this by 'faking' gravity always having it point in the opposite direction as the normal of the terrain segment the vehicle is currently driving on.

# Answer
> 0 votes
Friction coefficient is equal to tangent of the maximum angle before the item will slide.

You need to set coefficient greater then 1. There is a function in the Settings class - MixFriction. It's used to calculate the friction coefficient between surfaces, by default it's a geometric mean, you can change this too.

---
Tags: 2d, android, physics, libgdx, box2d
---


title: Blender animation to XNA distortion bug

text:
# Question
Title: Blender animation to XNA distortion bug
I followed the instructions on the following video: http://www.youtube.com/watch?v=SissgQ0IXvk

I'm using XNA 4.0 and Blender 2.69

I export the model with animation to a .FBX file.

The animation is a man waving

Here is what it looks like in Blender:

And here is how it renders in XNA:

The arm where the animation occurs is greatly distorted.

I believe the error occurs in the AnimationPlayer class:

```
        /// <summary>
    /// Helper used by the Update method to refresh the WorldTransforms data.
    /// </summary>
    public void UpdateWorldTransforms(Matrix rootTransform)
    {
        // Root bone.
        worldTransforms[0] = boneTransforms[0] * rootTransform;

        // Child bones.
        for (int bone = 1; bone < worldTransforms.Length; bone++)
        {
            int parentBone = skinningDataValue.SkeletonHierarchy[bone];

            worldTransforms[bone] = boneTransforms[bone] *
                                         worldTransforms[parentBone];
        }
    }

    /// <summary>
    /// Helper used by the Update method to refresh the SkinTransforms data.
    /// </summary>
    public void UpdateSkinTransforms()
    {
        for (int bone = 0; bone < skinTransforms.Length; bone++)
        {
            skinTransforms[bone] = skinningDataValue.InverseBindPose[bone] *
                                        worldTransforms[bone];
        }
    }

```

I think the bug can be fixed by editing the code above, I just don't know how to do it. Can somebody help me fix this distortion bug?

Here is a link to the project source code: http://www.mediafire.com/download/ps5ocf1nxbfgrru/SkinningSample\_4\_0.zip

Here is a link to the Blender file: http://www.mediafire.com/download/vrt8h1p83vkd76g/wave.blend

# Answer
Found the problem. XNA's content pipeline doesn't seem to be able to handle animated FBXs correctly. So XNA has a bug. Luckily Blender 2.68a and older has a "fix" for this. Just check "XNA rotation animation hack" when exporting the FBX.
> 0 votes

---
Tags: xna, c#, matrix, blender
---


# Question
Title: Set value in an array[3], that the sum of all three values is always 1.0
So I'm working on a Civ like game right now and want to have a setting how taxes are split in gold income, science and luxury goods.

```
private double[] rate = new double[] { 0.4, 0.6, 0.0 };

```

now I wanted to add a methode to change one of the values to a higher or lower value but maintain the overall sum of 1.0 (100%) but I'm stuck here with how to take or add values evenly from the other two rates

```
    public void setRate (int index, double r) {
    if (r < 0.0) {
        throw new IllegalArgumentException("Invalid Rate");
    }

    double diff = r - rate[index];
    if (diff > 0) {

        // ?

    } else if (diff < 0) {

        // ?

    }
    rate[index] = r;
}

```

**EDIT for amitp:**

```
public void setRate (int index, double r) {
    if (rate[index] = 1.0) {
         for (int i = 0; i < 3; i++) {
              if (i != index) {
                  rate[i] = (rate[index] - r) / 2;
             }
        }
    } else {
        for (int i = 0; i < 3; i++) {
            if (i != index) {
                rate[i] = rate[i] * (1.0 - r) / (1.0 - rate[index]);
            }
        rate[index] = r;
        }
    }

```

# Answer
> 1 votes
I think the simplest approach is to *rescale* the values.

The values other than the one you're setting currently sum to `1.0 - rate[index]`. You want them to sum to `1.0 - r`. You can therefore scale each of them by `(1.0 - new_value) / (1.0 - old_value)` to preserve the sum.

```
public void setRate (int index, double r) {
    for (int i = 0; i < 3; i++) {
        if (i != index) {
            rate[i] = rate[i] * (1.0 - r) / (1.0 - rate[index]);
        }
    }
    rate[index] = r;
}

```

This solution avoids:

1. Different code for positive and negative changes
2. Having to handle underflow (something + diff going below 0.0) and overflow (something + diff going above 1.0)
3. A value going from zero to non-zero, or vice versa. If the player set something at 0, then they probably want to keep it there.

Side note: a geometric interpretation is that your three values are coordinates in a cube. You constrain `x + y + z = 1.0` so that puts you on an equilateral triangle embedded in the cube. Thinking about it this way helped me come up with the above solution.

# Answer
> 0 votes
You could divide diff by two and then subtract it or add it accordingly to the other two.

```
double diff = r - rate[index];
double change = diff/2 * -1; //we need to reverse the operation

for(int i = 0 ; i < 3; i++)
{
    if(index != i) rate[i] += change;
}

```

Still you should be careful for number precision errors. For that you could use an int\[\] where all values sum up to 100.

# Answer
> 0 votes
One way to do this is to add to the indexes' value by its self multiplied by `diff`. `rate[i] = rate[i] + rate[i]*diff` where `i` is the other to values other than `index`

```
    double d = 1 - rate[index]
    double diff = rate[index] - r;
    rate[index] = r;
    index = (index + 1) % 3;           // increment and wrap around index
    rate[index] += diff*rate[index]/d;
    index = (index + 1) % 3;           // increment and wrap around index
    rate[index] += diff*rate[index]/d;

```

Hope that helps.

---
Tags: java
---


# Question
Title: Can I sell games made with LibGdx on Steam
my question is pretty self-explanatory, there is any technical or legal issue in selling libgdx games on steam?

**EDIT**

It is possible to show some kind of evidence, maybe a exemple of a game that is made with libgdx and already is on steam?

# Answer
No, there's no technical or legal issue why you can't sell your LibGDX game on Steam.

However -- and this is not specific to any platform or library -- your game needs to be pretty good for it to get their attention.
> 3 votes

# Answer
libgdx is under the apache 2.0 license meaning that you can use it freely in both for-profit, non-profit,open-source and closed source games. Selling a game on steam makes it for-profit and likely closed source so you will be fine as long as you read at least once through the apache 2.0 lisence (it's not that long).
> 4 votes

---
Tags: libgdx, steam
---


# Question
Title: Server Side : How to manage "delay" action/event like attacking?
at the moment I'm writing a game server, so I made an event "handler". I mean, if a player send to the server "I move" it fire a function, so I think I'm doing well at the moment.

But there's a problem and I don't know how to handle it. Lets take an example.

When a player want to attack he need to press a key one time, and it will attack automaticly every second, that means the server receive one packet with "I attack" and the server handle it, But I don't know how to make the player attacking every second correctly. It's kinda hard to explain I'm sorry ! So what I'm doing at the moment is, if the server receive from the player "I attack" I start a timer for the player which call a function every second. And I do that for every player but, I think that is not a nice idea. Should it be better to make one big timer ? If yes, which interval should I use ? 100ms or more ?

Well I hope you understood me, I know I didn't explain it well and sorry for that ! Thanks in advance for your help.

# Answer
It sounds like you are using some kind of callback system to handle incoming messages. This is entirely reasonable but it does not obviate the need for a game loop. In fact, "one big timer" idea is basically exactly the same as a game loop. A typical client might have a loop like:

```
while(!exited()) {
    handleInput();
    sendReceiveNetworkMessages();
    updateGameObjects();
    render();
    window->flipBuffers();
}

```

In a client, you want to run as fast as possible. If V-sync is enabled, then `flipBuffers()` will block and prevent the loop from running too quickly. That is why we don't use timers typically for game loops, because we need it to start over immediately to write the next frame. On a server, this might look like:

```
while(!done()) {
    time start = now();
    sendReceiveNetworkMessages();
    updateGameObjects();
    waitUntilTime(start + 100ms);
}

```

There is much less work to do, because we don't need to render the game world. But we still need to run the game logic, create and destroy entities, damage players, handle logins, etc. The architecture you describe as using seems to be based on reaction to network messages. When a player requests to attack, they kick off a timer that repeatedly attacks. This is putting the state of a player (i.e. whether they are "continuously attacking") into the timer manager. While it might seem simple to code, this is likely not a good idea because it requires extra code to handle cancelling the timer, etc. It is cleanest to store this state as explicitly as possible, as opposed to implicitly in the presence or absence of a timer.

You probably have a `Player` object on the server for each connected player. They would have a boolean field `isAttacking`, and a time field `lastAttack`. Then during object update, if `lastAttack + 1sec < stepStart + stepDuration`, we say the player can attack that step. Then crucially we update `lastAttack = laterOf(lastAttack + 1sec, stepStart)`. Why not just say `lastAttack = stepStart`? Because we want the player to attack once a second, and otherwise depending on how our steps actually line up with the 1 second interval, we might be off by 100ms, which wouldn't be fair to multiple players. On a client this usually is ignored because a frame is 16 or 30ms, so the error there is negligible.

Now the response to the network message is just to set or clear the `isAttacking` flag in the player. Thus the architecture is driven by the game loop, rather than in response to messages. The `laterOf` function ensures that we don't need to worry about the `lastAttack` time being in the far past if the player stops attacking, then later starts up again. If we didn't do this, they would attack every frame until we had added enough 1sec intervals to catch up!

Note that timers provided by the language or OS are probably expensive. A small constant number is fine, but one for every player will not scale to many users.
> 1 votes

---
Tags: architecture, server, events
---


# Question
Title: Import FBX with multiple meshes into UDK
I used this script to generate a few buildings that I was hoping to import into UDK. Each building is made of about 1000 separate objects. When I export a building as FBX and import the file into UDK it breaks it up into its individual objects again, so I was wondering how I would avoid this. Whether there was a tool to combine all of the objects into one mesh automatically before exporting or if I could prevent UDK from breaking them upon import.

# Answer
> 1 votes
One way would be to have one building in your scene visible (hide everything else)

Then convert one of the pieces into an editable poly - then click the box next to add, and pick all the pieces in the box. This will make one editable poly.

I would recommend removing the xform and placing the pivot to the base of the building to help with importing.

**BUT** this method will not remove the inner poly's of all the buildings, for that you would need to edit all the objects individually and stitch them together. I think it would be quicker to build them from scratch, but use the buildings you generated as reference.

The inner poly's will vastly increase the total polycount of each building and will generally be a waste of memory. So it would be better to optimize in the long run.

# Answer
> 1 votes
Actually, UDK now has a "Combine Meshes" setting on the import settings, check that and you're probably ok.. I lose some materials once in a while, but then again, my UDK has shown some unheard-of problems, so it's probably just me. Another choice would be to combine them within the 3D editing program before exporting.

---
Tags: udk, 3dsmax
---


# Question
Title: Importing FBX with multiple meshes in UDK
I need to import into UDK a several amount of FBX models (representing buildings) which are composed by various submeshes (walls, windows, roof...). I need to keep the individual meshes (can't use the merge option) but I also need to work with the building as a whole. Do you know if this is possible? How?

Also, is there a way to keep the textures assignment for the FBX models after importing them to Unreal? Doing the process manually (importing model, importing texture, assign to the material, assign the material to each mesh and submesh) for 100 or 200 models (to import an entire city from City Engine), isn't viable.

# Answer
Not much of an answer perhaps, but in my experience with other libraries, you are typically expected to maintain a single mesh per file import. Unity, IIRC, has the same deal with its FBX imports.

Really, there is nothing particularly problematic about simply separating the pieces into individual files, is there? You just need to track their positioning offsets in the original file, before you start splitting the parts out into their own FBXes.
> 1 votes

# Answer
Perhaps you can make a prefab after you have finished with the editing? I mean, bring it all into a blank map, edit as wished, and then make a prefab of that and access it from another project..
> 0 votes

---
Tags: textures, 3d-meshes, udk, fbx, import
---


title: Change velocity of CharacterController?

text:
# Question
Title: Change velocity of CharacterController?
I'm trying to change the velocity of a character controller component on a Third Person Controller, but when I try to change it, the console says the velocity is read only. This is my code.

```
P.GetComponent(CharacterController).velocity = 0;

```

(P is my player GameObject variable)

So, any ideas on how to change this?

Thanks, Chris.

# Answer
As that error clearly states, that value is read-only; you cannot set it directly. The 'velocity' property of a CharacterController is a side-effect of movement commands to the object. So you attempt to move the object, then collision detection is applied, then the 'velocity' property is set to tell you how much the object actually moved. The relevant documentation:

> Note: The velocity returned is simply the difference in distance for the current timestep before and after a call to CharacterController.Move

The way to move a CharacterController is using the Move() function.
> 1 votes

---
Tags: unity
---


# Question
Title: Updating entities in response to collisions - should this be in the collision-detection class or in the entity-updater class?
In a game I'm working on, there's a class responsible for collision detection. It's method `detectCollisions(List<Entity> entities)` is called from the main gameloop.

The code to update the entities (i.e. where the entities 'act': update their positions, invoke AI, etc) is in a different class, in the method `updateEntities(List<Entity> entities)`. Also called from the gameloop, after the collision detection.

When there's a collision between two entities, usually something needs to be done. For example, zero the velocity of both entities in the collision, or kill one of the entities.

It would be easy to have this code in the `CollisionDetector` class. E.g. in psuedocode:

```
for(Entity entityA in entities){
    for(Entity entityB in entities){
        if(collision(entityA, entityB)){
            if(entityA instanceof Robot && entityB instanceof Robot){
                entityA.setVelocity(0,0);
                entityB.setVelocity(0,0);
            }
            if(entityA instanceof Missile || entityB instanceof Missile){
                entityA.die();
                entityB.die();
            }
        }
    }
}

```

However, I'm not sure if updating the state of entities in response to collision should be the job of `CollisionDetector`. Maybe it should be the job of `EntityUpdater`, which runs after the collision detection in the gameloop.

**Is it okay to have the code responding to collisions in the collision detection system? Or should the collision detection class only detect collisions, report them to some other class and have that class affect the state of the entities?**

# Answer
Well, `CollisionDetector` sounds like a pretty generic class name and I guess you might want to re-use it for other games as well. Adding game-specific logic like `if(entityA instanceof Robot ..` really defeats that purpose unless every game will have a `Robot` class...

I'd let the entity decide what to do when a collision happens. So your entity base-class or interface could have a `OnCollision` method which will then be called by your `CollisionDetector`. Usually you'll pass the object that collided with the entity and some other relevant information (maybe contact-points) as parameters to the callback.

You tagged your code as *pseudo-code*, so I'm not sure how close to reality it is, but right now you're checking every collision twice (because of the two for loops).
> 1 votes

# Answer
You can send messages to each entity in the collision, containing the collision\_type of the other object, it's mass and velocity at the time of collision, and the contact point on the messaged entity. Entities handle the messages for collision\_types they want to respond to, and ignore the others.

Also, a couple of nice optimizations can be done.

1) Start the inner entity loop at the current position of the outer loop + 1. In C++:

```
for(int a = 0; a < entities.size()-1; ++a)
    for(int b = a+1; b < entities.size(); ++b)
    {
        if( collision(entities[a], entities[b])
        {
            ....

```

2) If you keep a pointer to the last entity you collided with in each entity, for some collision\_types you can ignore collisions with the same entity in a subsequent loop.
> 0 votes

---
Tags: collision-detection, game-loop, oop
---


title: SDL render to a texture

text:
# Question
Title: SDL render to a texture
I am trying to create a button for my game there are lots of similar buttons so using an image for each one is a bit inefficient. So I want to load an image then copy some text over it and render that to the screen. But it just doesn't render anything, it just gives me a transparent surface.

```
SDL_Texture* button = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA888, SDL_TEXTUREACCES_TARGET, 200, 50);
SDL_SetRenderTarget(renderer, button);

SDL_Texture* border = IMG_LoadTexture(renderer, "border.png");
SDL_Texture* text = SDL_CreateTextureFromSurface(renderer, TTF_RenderText_Blended(font, "new race", color));

SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, border, NULL, NULL);
SDL_RenderCopy(renderer, text, NULL, &text_centered);
SDL_SetRenderTarget(renderer, NULL);

```

Then I do some extra stuff and finally:

```
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, background, NULL, NULL);
SDL_RenderCopy(renderer, button, NULL, &position);
SDL_RenderPresent(renderer);

```

But it just rendered the background not the button, that indicates that the textures I tried to render to button where not rendered and it is still just a blank texture. I already set SDL\_RENDERER\_TARGETTEXTURE but it just doesn't work.

UPDATE:

I found out that the problem was that the format and the access where passed in the wrong way, I corrected it and now when I compile there is an access violation, this is because I pass SDL\_TEXTUREACCES\_TARGET as the access argument, if I pass SDL\_TEXTUREACCES\_STATIC there is no such violation, the problem is that I can't use SDL\_SetRenderTarget if it is static, it needs to be target (which causes an access violation error).

# Answer
I found out that the access violation was a bug in SDL that only happens in some drivers (intel graphics in my case) if I use SDL\_RENDERER\_SOFTWARE instead of SDL\_RENDERER\_ACCELERATED it works, so it is pretty much depending on your graphics card and its drivers.
> 2 votes

---
Tags: textures, rendering, sdl
---


# Question
Title: How do i initialize and use a Texture Array? LibGDX
First of all, I am new to Java and LibGDX..

What I am trying to do is Load my texture images into an array so that I can reference them in my drawing code by number, rather than by name. I am drawing a tile map.

Instead of this:

```
tile1 = new Texture(Gdx.files.internal("grass.png"));
tile2 = new Texture(Gdx.files.internal("dirttile.png"));
tile3 = new Texture(Gdx.files.internal("watertile.png"));

```

I would like it to be more like:

```
tile[1] = new Texture(Gdx.files.internal("grass.png"));
tile[2] = new Texture(Gdx.files.internal("dirttile.png"));
tile[3] = new Texture(Gdx.files.internal("watertile.png"));

```

..so that later I can draw them by which tile I need..such as

```
tileType = worldMap[i][j]; //will be an int number
batch.draw(tile[tileType], tileX, tileY);

```

I can't figure out how to initialize array and load textures into it though in order to do this, without getting errors.

---

Basically I need to draw my map based on numbers I have in a tile map like this:

```
 int worldMap[][] = {
            { 1,1,1,1,1,1,1,1,1,1 } ,
            { 1,1,1,1,1,1,1,1,1,1 } ,
            { 1,1,1,1,1,1,1,1,1,1 } ,
            { 1,1,1,3,3,3,1,1,1,1 } ,
            { 1,1,1,3,3,3,1,1,1,1 } ,
            { 1,1,1,3,3,3,1,1,1,1 } ,
            { 1,1,1,1,1,1,1,1,1,1 } ,
            { 1,1,1,1,1,1,1,1,1,1 } ,
            { 1,1,1,1,1,1,1,1,1,1 } ,
            { 1,1,1,1,1,1,1,1,1,1 } ,
    };

```

I need to draw the map tile based on the numbers in that map... 1 = grass 2 = dirt 3 = water etc.... Still no luck getting the array working.

# Answer
> 1 votes
You can initialize tile1, tile2 and tile3 and then you can add them to Array.

```
tile1 = new Texture(Gdx.files.internal("grass.png"));
tile2 = new Texture(Gdx.files.internal("dirttile.png"));
tile3 = new Texture(Gdx.files.internal("watertile.png"));

```

Here is how you will initialize Array:

```
Texture[] tile = {tile1, tile2, tile3};

```

# Answer
> 0 votes
Having a list of textures in an array is not a great idea. What if you decide to put them into a texture atlas later (which is generally more efficient than loading a bunch of files)? What if you change the order of a file in the middle? You'll have to re-order a bunch of your data.

A more flexible approach would be to keep not just a flat file name or index, but a combination of the two; perhaps in a simple class, or a hash:

```
class Tile {
    private String filename;
    private int index;
}

// or ...

// filename => index
Map<String, int> textureIndicies = new HashMap<String, int>();

```

In any case, about your original problem: I suggest you use a dynamic class like `ArrayList` here instead of a flat array. Why?

* Easier to add and remove images from it
* Easy to get the element at a particular index
* Approximately the same average runtime performance as an array

The choice is yours, though, with what approach you go with.

---
Tags: libgdx, tilemap, maps, tiles
---


# Question
Title: Most efficient way to do 2d tiles (VBO vs Instancing)
Ok so I am looking at building a game that uses 16\*16 tiles, and renders anywhere from 400,000 to 1,000,000 tiles onto the screen at any given time. The tiles will be destroyable .

What is the most efficient way of rendering them in OpenGL (3.3)?

How does a VBO compare to instancing? (Would instancing be any good in this situation?)

# Answer
> 1 votes
Either way should be fine (although note that you need buffer objects in order to do instancing). Your primary bottleneck is going to be elsewhere: fillrate, overdraw and ROP.

# Answer
> 0 votes
Using a VBO means that the data for drawing will sit in GPU memory, which is better (performance wise) than if it would be in main memory. Using instancing means drawing multiple instances of the same geometry (using different parameters based on the instance ID).

Those things do not exclude each other! You can draw with instancing from a VBO - if many of your tiles will share the same geometry this would be a way to draw it.

# Answer
> 0 votes
Since it's about 2D tiles and 1,000,000 is an awfully big number (so each tile will be a small rectangular area a few pixels big), the most efficient way of doing this would be to draw a textured fullscreen triangle. Really, no kidding. There's no need for geometry here.

UXGA only has 1,920,000 pixels total (1.9 pixels per tile), and 1080p will have just about 2.07 pixels per tile at 1M tiles. That's perfectly adequate for drawing a textured quad (or triangle, which is more efficient, avoiding double shader invocation on the diagonal).

Have two PBOs to update the texture, and set alpha to zero (or color to black, or whatever) when you "destroy" a tile.

---
Tags: opengl, efficiency
---


# Question
Title: How do I make collision detection more effective?
In the game I am developing, there are 220 circles that are not moving. One of the circles is moving and in every update, it iterates through an ArrayList that contains all the circles and check if it collides with them and if it does, then its velocity is set to 0.

Sometimes, it works perfectly. However,most of the time, when the moving circle collides with another circle, it stops late sometimes when the ball is already inside the other circle. How can I deal with this?

I am using LibGDX with Java.

# Answer
> 2 votes
Your problem is that you are checking for a collision and then stopping, this means that if your frame places you to far into an object you are now stuck. To solve this you have to solve the equation of exactly where both object were when they hit one another.

So you have to find where the following is true:

```
|t*v1+p1-t*v2+p2)|=|r|

```

where t is time v is the velocity r is the radius of the circa;e and p is the position.

So some math:

```
|t*v1+p1-t*v2+p2|=|r|

|t*(v1+p1-v2-p2)|=|r|

t=|r*(v1+p1-v2-p2)|

```

(in case you don't know || means length as in Pythagorus a^2+b^2=c^2)

you now have the exact moment of collision and can multiple calculate the position of both object at the moment of collision.

That should at least solve your stickiness problem, you can go here: Efficiently detecting objects inside multiple radius to solve your efficiency problem in order to also solve your fps problem.

# Answer
> 1 votes
A simpler way, that will also speed up your program, is to check if your circle is moving towardas the other circle before check for a possible collision. You can do in it in this way:

```
vector2 p;
p.x = other.position.x - your.position.x;
p.y = other.position.y - your.position.y;
if(p.x*yourSpeed.x + p.y*yourSpeed.y > 0
{
 //check for collision;
}

```

look at this: http://compsci.ca/v3/viewtopic.php?t=14897

---
Tags: java, collision-detection, libgdx
---


# Question
Title: What is missing from SDL for it to gain more widespread adoption?
As I understand, SDL offers abstractions that let you make windows, handle input and audio much easier than doing so directly with the low level APIs provided by several operating systems.

However, it seems that a lot of games, both indie and AAA, don't use it, and I would like to know why. This makes me suspect that there may be areas where SDL is lacking, such as features, performance, or robustness, when compared to platform-specific APIs.

Apart from platform support, that is, considering only the platforms SDL supports, I do not understand what would keep a developer from using SDL for their game, since I feel like, based on my admittedly limited knowledge, it'd be much smarter to use SDL on the platforms that do support it.

# Answer
**SDL introduces an additional dependency**

While many platforms support it, it is not a part of the regular distribution of all of those platforms, so users must download and install it themselves. One such platform is Windows, and assuming that your target market is divided in proportions similar to the Steam Hardware Survey, that means that ~95% of your potential users probably don't have SDL.

If you're dependent on users downloading and installing SDL correctly themsleves, *you will get burnt*. You'll encounter problems such as users failing to get the correct version, failing to get the DLLs into the correct directories, incorrectly mixing 32-bit SDL with 64-bit programs (or vice-versa), and potentially causing version-conflicts with other programs that may use SDL. All of those will cause you support headaches and generate a bad reputation for your program.

The solution to this is knowledge, of course. Not on the part of your users (nobody ever reads readme files) but on your part. You need to know that this can be a problem, and you need to package the correct SDL binaries with your program's installer, then install them in your program's own directory so as to avoid conflicts with other programs. Either you're prepared to go this route or you risk problems for ~95% of your potential users.
> 1 votes

---
Tags: sdl
---


# Question
Title: How to sync towers and enemies in Tower Defense?
I'm going to build a tower defense (like) game.

In a heavy tower defense, it takes time to processing.

So, if i set a time interval, it costs interval+processing time so it's not fair.

If i make a processing unit run every 100ms and process all things, it'll be fair but it costs more. And this is not good for flying weapon(like bombs).

Any another way or just use 100ms process unit?

# Answer
This sounds more like a "how do I make a game loop question?" to me. The game loop should control the timing of all your units, and the frequency in which everything is redrawn. Yes, every pass of the loop takes certain amount of time to complete. Depending on how you want to set up your game loop, you can either try to control how much time each pass takes, or you can update each unit based on the amount of time that has passed.

There is a difference between draw rate and update rate. The draw rate would be the frames per second (fps) that you render the game at. You should use a fps that will give you smooth animation for what you are doing. For example, television uses 24 fps, this is enough to fool our brains into thinking that we are seeing fluid motion. On the other hand, some games have fast moving objects that do not look smooth at 24 fps, which is why they might run at 60 fps.

When it comes to updating the objects in your game, if you can get everything done within the amount of time allotted per frame redraw then you are doing good. For instance, if you have set your game up to run at 25 fps, then you have 40ms of processing time in which to update every unit and redraw the frame. That's 1000ms / 25 frames = 40 ms per frame. The amount of time you have to update would be 40ms less the time it takes to redraw the frame. If updating takes longer than this allotted time, you will start to run into trouble, because the extra time spent updating will delay the next frame redraw. This will effect how good your animations look.

If you have a lot of units that need updating and it takes too long to process them all in a single pass, it is possible to update half the units on one frame, and the other half on the next. This will reduce the update time per frame. Or maybe, updating usually gets done on time, unless you have to do a big operation, like pathfinding for 20 different units. Here you could do normal updating for the rest of the units, do the pathfinding for 10 units on one frame, and pathfind for the rest on the next. This small delay for a few units will go unnoticed.

Check out dewitters-gameloop for more details on this.

Regardless, 100ms is probably too long of an interval. Your animations will most likely look choppy at this rate.
> 1 votes

---
Tags: synchronization, tower-defense
---


title: Multiple gravity "zones" in a world

text:
# Question
Title: Multiple gravity "zones" in a world
I have a world that I want to divide in two like this:

```
 ____________________
|                    |
|                    |
|        A           |
|                    |
|                    |
|____________________|
|                    |
|                    |
|        B           |
|                    |
|                    |
|____________________|

```

And I want the gravity in A to go up and in B to go down.

How can I implement a world like this using Box2D?

# Answer
Create static bodies A and B, each of them with rectangular fixtures with `b2Fixture::setSensor(true)`.

Utilize the `b2ContactListener::BeginContact` and `b2ContactListener::EndContact` to determine when a body is entering or leaving areas A or B. When one of these events is detected, modify the `gravityScale` of the dynamic body accordingly. In pseudocode these functions should look like this:

```
function BeginContact(contact){
    /* Do some preliminary tests to determine this is a collision between
    a sensor and dynamic body, and store them in local vars staticBod and dynamicBod*/
    //Assume the gravity exerted by each sensor body is stored in the userdata
    dynamicBod.SetGravityScale(dynamicBod.GetGravityScale() + static_cast<float>(staticBod.GetUserData()));
}

```

The `EndContact` function should just undo that:

```
function EndContact(contact){
    /* Do some preliminary tests to determine this is a collision between
    a sensor and dynamic body, and store them in local vars staticBod and dynamicBod*/
    dynamicBod.SetGravityScale(dynamicBod.GetGravityScale() - static_cast<float>(staticBod.GetUserData()));
}

```

You also need to call `b2World::SetGravity` to some reasonable vector (e.g. (0,-1))
> 1 votes

---
Tags: box2d
---


title: Freeze Player position temporarily?

text:
# Question
Title: Freeze Player position temporarily?
I'm making a 2D sidescroller (although it's technically being made in 3D), and I need to freeze a player's position temporarily. With a RigidBody, this would be simple, but I can't think of how to do it with a First Person Controller besides saving a player's position and setting it back to that position every frame, which is very inefficient.

# Answer
Save the linear velocity and angular velocity. Then zero them out on the rigid body. The reapply them when you're ready for the body to move again. Something like a coroutine will work just fine (mine is written in C#, but you can convert it easily enough):

```
void Update() {
    if (Input.GetKeyDown(KeyCode.T)) {
        StartCoroutine(PauseMovement());
    }
}

IEnumerator PauseMovement() {
    //Backup and clear velocities
    Vector3 linearBackup = rigidbody.velocity;
    Vector3 angularBackup = rigidbody.angularVelocity;
    rigidbody.velocity = Vector3.zero;
    rigidbody.angularVelocity = Vector3.zero;

    //Finally freeze the body in place so forces like gravity or movement won't affect it
    rigidbody.constraints = RigidbodyConstraints.FreezeAll;

    //Wait for a bit (two seconds)
    yield return new WaitForSeconds(2);
    //And unfreeze before restoring velocities
    rigidbody.constraints = RigidbodyConstraints.None;
    //restore the velocities
    rigidbody.velocity = linearBackup;
    rigidbody.angularVelocity = angularBackup;
}

```
> 1 votes

# Answer
I am no expert but I have just done this in C# (freeze the player for 2 seconds as penalty) handled through a `canMove` bool around the movement handler. I thought this was the easiest way to do this and so far it has served me just fine!

Before the movement handling loop:

```
if (player.status == penalised)
{
   if (checkerVar >= (levelTimer - 2)
      player.status = normal
}

```

This bit sets the player status to normal if it's been 2 seconds since the `checkerVar` is set (which happens when hitting a wall in my case). `LevelTimer` is an independent variable that counts down from when the level begins.

```
else
{
    // handle all movement
    bool canMove = false;
    switch (playerAction)
    case (tile in the direction the player wants to move in == tileType::WALL)
 {
      player.status = penalised;
      checkerVar = levelTimer;
 }
case (tile in the direction the player wants to move in == tileType::FLOOR)
      canMove = true;
      // etc for all other directions

// canMove is only set to true when the player is not hitting a wall
if (canMove)
{
    player.move();
}

```

Granted, I found this way easy because I already had a level timer to work with, so penalising the player by counting seconds was quite straightforward. FWIW rendering for me (2D) happens in a separate function, where I use the status of the player to render a different skin if they are penalised - nothing else. Hope this helps!
> 0 votes

# Answer
Just don't use the First-Person controller that Unity comes with. It's simply a pre-written script attached to a Character Controller; you could easily just write your own movement script (that's what I do, and it's the second chapter of the book I'm writing).

Since the movement is simply a batch of code within a script you wrote, then any time you don't want to move the object simply don't run that code. Just wrap all the movement code with `if (canMove) {` and then set `canMove = false` when you want to player to freeze.

(incidentally, if you're making a 2D side-scroller then why are you using a first-person controller? forgive me making the obvious point, but er your game isn't first-person)
> 0 votes

---
Tags: unity, javascript
---


title: HTML5 moving image, doesn't move

text:
# Question
Title: HTML5 moving image, doesn't move
Why my image doesn't move? Can you help me ...

```
<script>
   window.requestAnimFrame = (function(callback) {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
        function(callback) {
          window.setTimeout(callback, 1000 / 60);
        };
      })();

      var canvas = document.getElementById('myCanvas');
      var ctx = canvas.getContext('2d');

      ctx.font = 'bold 20pt Calibri';
      ctx.fillText('Traffic Light SIMULATION', 250, 25);

      function animate(imageObj, canvas, ctx, startTime) {
        // update
        var time = (new Date()).getTime() - startTime;

        var linearSpeed = 100;
        // pixels / second
        var newX = linearSpeed * time / 1000;

        if(newX < canvas.width - imageObj.width / 2) {
          imageObj.x = newX;
        }

        // request new frame
        requestAnimFrame(function() {
          animate(imageObj, canvas, ctx, startTime);
        });
      }

    var imageObj = new Image();
      imageObj.onload = function() {
        ctx.save();
        ctx.translate(imageObj.width,0);
        ctx.scale(-0.5,0.5);
        ctx.drawImage(imageObj,200,100);
        ctx.restore();
      };
      imageObj.src = 'car.png';

      setTimeout(function() {
        var startTime = (new Date()).getTime();
        animate(imageObj, canvas, ctx, startTime);
      }, 2000);

</script>

```

# Answer
You have to draw the image at every frame when using canvas, you render the image once when calling `ctx.drawImage`, and thereafter you don't render anything to the canvas, so it stays the same.
> 1 votes

---
Tags: html5, webapp
---


# Question
Title: How are 2D transformation matrices applied to their targets?
I understand mathematically how transformation matrices work, in that a transformation matrix multiplied by a vector results in a new vector, and we use the matrices for rotation, translation, etc. I also understand that in 3D, the transformation matrices are applied to every vertex of each model in order to transform them, although that's basically the extent of my understanding vis-a-vis 3D transforms, and maybe even that understanding is a little wrong/simplistic.

However, many game engines/graphics rending libraries are designed with the intention of rendering 2D graphics (ex: Flash, XNA, SDL, Allegro), although I know at least some of them are really 3D under the hood. These engines allow the programmer to use transformation matrices to manipulate 2D entities, to do something like implementing a camera, for example. But I don't understand what the transformation matrices I'm plugging in to the engine are being multiplied by in order to perform the transformation. For a while I assumed it was applying the transformation matrix to each pixel of the original image, but that doesn't seem right to me.

So what vectors are the transformation matrices being multiplied by in the 2D transformations? Was I right, and it's really a per-pixel operation? Or does it do some kind of 3D magic under the hood?

# Answer
If the engine is using the 3D graphics hardware under the hood, then it still has vertices, even if it's a 2D game. The models might be very simple—a rectangle for each sprite, for instance. But the matrices would still apply to the vertices, just as they do in a 3D game.

If the engine doesn't use 3D graphics hardware under the hood, but does all its own rasterization, then the matrices still apply to the position (and scale and rotation, if applicable) of each sprite. The engine would use these to work out where each sprite should be drawn on screen.

In a sense, the matrices *do* also apply to each pixel, indirectly, since a sprite's texture gets pulled along when the sprite or its vertices move. However, the engine would not *literally* be applying the matrix to the position of each individual pixel.
> 2 votes

---
Tags: 2d, matrix, transformation
---


# Question
Title: Can I extract Flash SWF sprite frames to bitmaps?
I want to create the 2D graphics of my game in Flash Studio, but then get all the frames from my SWF movies into C# for further work in Unity3D.

I find it easier to create nice smooth animations in Flash Studio. But then I also want the performance Unity gives and the multi-platform support as well.

How can I do this?

# Answer
Have you tried using ShoeBox it has many utilities for SWF files. One of those allows you to create spritesheets from a SWF file.
> 3 votes

# Answer
While not exactly what you're looking for, this post on reddit might be of interest - an upcoming tool for rendering swf animations in Unity, from the sounds of it the performance is good and you still retain the cross-platform functionality.
> 1 votes

# Answer
You might try using Flump: http://threerings.github.io/flump/

You'll have to port one of the existing client libraries to Unity, but the client libs are simple and should be pretty easy to port. Most of the heavy lifting is done by the exporter.
> 1 votes

# Answer
I'm guessing you mean "Flash Pro". You can export a sprite sheet directly from inside Flash Pro. Instructions are available on Adobe's web site.

http://helpx.adobe.com/flash/using/create-sprite-sheet.html

This will take a snapshot of each frame of the animation, at the interval for the frame rate you specify, then combine all the frames into a grid in a single image.

You can then load the sprite sheet into Unity to create the animation. There's a tutorial on raywenderlich.com showing how to do this:

http://www.raywenderlich.com/61532/unity-2d-tutorial-getting-started
> 1 votes

# Answer
There are a number of tools for this purpose. Flash itself has an option for something like Export to PNG Sequence. Texture Packer also can import a SWF. Yet another option, which I used to create the spritesheets for the HTML5 demo on my site, is Zoe, the spritesheet tool that comes with CreateJS.
> 1 votes

---
Tags: c#, unity, flash, swf
---


# Question
Title: C++ timer function acts as if time limit is instantly reached if it is less than 1 second
I'm trying to make a Snake clone with C++ and OpenGL/GLUT, but I've been having trouble with programming the timed input. I made a timer class, as you'll see below, to be used for the short time intervals allowed for input and movement. It's function *checkTime()* is called to start the timer. Then on following calls, it checks if the time limit (represented by the int variable *limit*) has been reached.

To test it, I set up a simple, looping console program, that displays keyboard input. When working properly, it displays what key is being held precisely at the point when the timer finds the time limit has been reached (it returns "true"). Given a limit of 1 second, it will only display current input every second. If it is given a value below 1 however, like 0.333, it will act as if the time limit has instantly been reached, and will display input instantly whenever a key is pressed. **How can I get it to only display the input every 0.333 seconds?**

*Also - I realize my method of doing things here may not be the best, given the tools I'm using. However, I'm curious why this won't work properly.*

```
#include <iostream>
#include "timer.h"
// Include all files necessary for OpenGL/GLUT here...

using namespace std;

Timer timer;

void update(int value)
{
    if (timer.checkTime())
    {
        if (GetAsyncKeyState(VK_LEFT))
            cout << "You pressed LEFT!" << endl;
        else if (GetAsyncKeyState(VK_RIGHT))
            cout << "You pressed RIGHT!" << endl;
        else if (GetAsyncKeyState(VK_UP))
            cout << "You pressed UP!" << endl;
        else if (GetAsyncKeyState(VK_DOWN))
            cout << "You pressed DOWN!" << endl;
    }

    glutTimerFunc(1000/60, update, 0);
    glutPostRedisplay();
}

```

timer.h

```
#pragma once

class Timer
{
public:
    Timer();
    bool            checkTime(int limit = 0.333);
private:
    unsigned long   getElapsed();
    bool            running;
    unsigned long   elapsed;
    unsigned long   start;
};

```

timer.cpp

```
#include "timer.h"
#include <ctime>

Timer::Timer()
{
    running = false;
    elapsed = 0.0;
    start = 0.0;
}

bool Timer::checkTime(int limit)
{
    (unsigned long) limit;

    elapsed = getElapsed();

    if (elapsed < limit)
    {
        return false;
    }
    else if (elapsed >= limit)
    {
        running = false;
        return true;
    }
}

unsigned long Timer::getElapsed()
{
    if (! running)
    {
        start = (unsigned long) clock();
        running = true;
        return 0.0;
    }
    else
    {
        return ((unsigned long) clock() - start) / CLOCKS_PER_SEC;
    }
}

```

# Answer
```
int limit = 0.333;

```

is the same as

```
int limit = 0;

```

because `int` has no decimal places. So you ether work in fixed point where the number is divided by a fixed amount, or floating point.

so for example if doing fixed point hundredths, you would use,

```
const int FIXED = 100;

unsigned long Timer::getElapsed()
{
    if (! running)
    {
        start = (unsigned long) clock();
        running = true;
        return 0;
     }
     else
     {
         return ((unsigned long) clock() - start) / (CLOCKS_PER_SEC/FIXED);
     }
}

```

and fixed could be

```
int limit = (unsigned long)(0.333 * FIXED);

```

I wouldn't define it like the above, but leaving it in form you would reconise.
> 1 votes

---
Tags: c++, input, timer, glut, timing
---


title: Estimated framerate for custom engine?

text:
# Question
Title: Estimated framerate for custom engine?
I've been writing my own engine with C++ and DirectX 11. I've got 3d models loaded in with diffuse maps, normal maps, and shadows. There's other things with the engine but my question doesn't pertain to those parts. What estimated framerate should I be getting from a simple cube with all the maps on it. And a moving shadow? Obviously my computer specs make the biggest difference. But lets say anywhere from Nvidia 500 series to 700. Personally I have a GT 750m. So whats a rough estimate of framerate to be getting? Dont want to keep building something that has a major framerate flaw.

# Answer
Play some game with your system. Check FPS you are getting. Analyze what is on the screen of the game and compare to yours. If your one cube is rendering slower than game screen, you are obviously doing something wrong.

I would expect one cube with all the normal stuff applied running atleast 500-1000fps on my computer. I can run games like Battlefield 4 with 50+ steady FPS.

Why are you developing an engine? Create a game for it and if it does not run with your system, you can start thinking about optimizations. I consider you graphic card as low end and thus, if your game runs on it, it should run on most of the gamers computers.
> 3 votes

---
Tags: c++, directx11
---


title: MonoGame hosted in a control/form

text:
# Question
Title: MonoGame hosted in a control/form
I would very much like to host my monogame window inside a Form so that I can take advantage of the nice gui elements in the C# framework when creating a simple level editor. I have looked online, but I am unable to find any working examples on how to do it. What is the state of this? Is it possible? I am using window 8.

Regards,

# Answer
Here is working example of Monogame + WPF interop: http://panthernet.ru/forum/index.php?/topic/21-monogame-wpf-interop-application/
> 1 votes

---
Tags: c#, monogame, tools, control
---


title: Games able to use 4+ core CPUs properly

text:
# Question
Title: Games able to use 4+ core CPUs properly
Are there any games that can really benefit from use of quad core CPU instead of two-core one like

Intel Core i3 4340 vs Intel Core i5 4590

Basically they are quite similar in terms of frequency/caches/features, but first one have only two real cores and second one have 4 real cores.

so are there any benefits for games for the second choice?

P.S. I believe that 4M of cache for two cores is quite better than 6M for 4 cores ;)

# Answer
> 9 votes
Games will not benefit that much by having 4 cores instead of two. Here's why.

**Basic Game Engine: 1 Thread**

The problem with graphics API like DirectX and OpenGL is that it must be runned on **one thread, and one thread only**. So a basic game engine will run all of the logic and render logic into a single thread. These engines will often use a time delta to synchronize the updating of the game world accordingly to the render FPS.

Ex.: libGDX, SDL

**Update and Render Loops Game Engines: 2 Threads**

These engines pose a clear separation between the update of the game world and its rendering. They will sometimes **separate these 2 logics into 2 threads** to gain a small performance gain but mainly **asynchronous rendering**. This means that the game can render at 400 FPS and the logic will still update at 60 FPS.

Ex.: Most high-end game engines, like Unreal, CryEngine or Frostbite

**Physics thread: +1 to X Thread**

Some games will like to put physics calculation in another thread so it doesn't mess with the updating or the rendering.

**Networking: +1 to X Thread**

Game with online gameplay will often use a separate thread because most networking engines are blocking, which means the thread will block until data is received.

**Disk IO operations: +1 to X Thread**

File management on large files can block a thread for a small amount of time, so most game engine will put disk IO operations on another thread.

**Summary**

Basicaly, **most game engines will use 1 or 2 threads** for the game's frame and will add some threads for other operations. But mostly, a game will only use 1 or 2 cores. If the game has heavy physics, like Frostbite engine for the BattleField series, then the game will start using more than 2 cores.

**CPU thread optimisation**

Mostly, a CPU will run different threads on different cores. But that may not always be the case. Like Joe Swindell said in the comments, games are not actually written to use cores, but when you write threads, you hope that they will run so that the CPU will distribute them to different cores.

**Conclusion**

What matters in the end is chosing the right CPU for the games you want to play or make. For small to medium games like Minecraft, then it is useless to buy a 4, 6 or 8 cores CPU. For high-end games, then 4 cores becomes the better option. If you want to program games, the more cores the better for compiling (depends on the compiler) but for the actual game, **2 cores is more than enough**.

**Cache P.S.**

Yes, 4MB cache on 2 cores will be better than 6MB cache on 4 cores. But this is not the most important thing to look for on a CPU. **It really comes down to the clock speed**.

---
Tags: optimization, multithreading
---


# Question
Title: What's the best program to learn/create 2d vector sprites?
I have Photoshop experience and a bit of drawing experience, and am looking to learn how to create sprites like this: http://www.lostgarden.com/2009/03/dancs-miraculously-flexible-game.html

Any tips on what app(s) to use and any reading material/online tutorials to get started?

Thanks!

# Answer
> 4 votes
Adobe Illustrator is a professional vector drawing tool. An open-source alternative would be Inkscape.

If you'd like to animate the sprites too, there's some basic animation-support in Illustrator. A better tool for vector-animations is Flash though.

These professional tools are rather expensive. If you just want to get your feet wet with vector graphics, it's maybe better to learn a free tool like Inkscape. You'll find some Inkscape tutorials over at: inkscapetutorials.wordpress.com

# Answer
> 2 votes
Well, Inkscape and AI are two good vector graphics editors (I use Inkscape myself) but to make things look good, you really need to have art skills. Also, if you want bone based animations, you're most likely going to have to write something yourself because I dont know of any solutions for that. However, to animate (hand made) you can just make spritesheets with whatever vector program you're using and copy the sprite and make your own sheet, changing each copy.

Also, heres a link on how to do skeletal animations http://www.catalinzima.com/2011/06/2d-skeletal-animations/

# Answer
> 0 votes
There is software specifically designed to make it easy to develop sprites and spritesheet. ToonBoom is a good example of this, however it is quite costly ($350,-) there might be cheaper/free ones out there with similar functionality but I wouldn't know for sure.

Most normal painting programs are not really suited for creating sprite sheets because you can't define 2D bones to stick arms and legs on (this makes it easy to at least make a rough pose with consistent art, before smoothing things out). However with enough persistence you could of course even do it in paint. And there might be plugins for photoshop and the likes that make this process easier.

Of course there are many tutorials on creating sprites:

# Answer
> 0 votes
From my experience as a game animator I would suggest to use 2 different programs:

first program to draw separate textures. I use "Corel Draw" for vector and "Gimp" at http://www.gimp.org/ for raster textures. Gimp is free.

second program you will need to create animation of your textures and to render a sprite sheet. I use "Anatomy Sprite Animator" tool at http://spritetools.com.

After that you can import transparent sprite sheet into your game creation system(I use Unity in 2D mode).

good luck!

---
Tags: 2d, vector-art
---