# Question
Title: Check every body's position and delete or not (box2d performance specific)
I have a simple game with a platform (a ground that's not infinitely long). During the game I have about 10-30 balls on average that'll fall off the platform. There's gravity so I think they'll keep falling until the end of the game. My question is should I put a function that check if position within boundary in the `render()` function, `render()` function is called in every frame. Or should I leave those balls falling. And let box2d keep on calculating their speed and velocity etc?

So basically I'm wondering which cost less, checking every body's position or calculating dropping object's velocity and position. I think they happen with same frequency, once per frame.

Or is this trivial for 10-30 balls and I can ignore it?

# Answer
if you never spawn new bodies above those 30 it probably won't matter letting them fall. Otoh it's trivial to delete them, and the check to do so needn't run every frame. Besides 30 iterations is nothing, even on mobile.
> 1 votes

---
Tags: box2d, performance, physics-engine
---


# Question
Title: Sending state diffs (deltas) and unreliable connections
We're building a realtime multiplayer game, in which each player is responsible for reporting its state on every iteration of the game loop.

The state updates are broadcasted using *unreliable UDP*.

To minimize state data sending, we've come up with a system that will send only deltas (whatever state data that was changed).

This method however is flawed, since a lost packet will mean that other players will not receive the delta, making the game behave in an unexpected way.

For example:

Assume that state is comprised of: { positionX, positionY, health }

```
Frame 1  - positionX changed --> send a packet with positionX only.
Frame 2 - health changed // lost !
Frame 3 - positionY changed --> send a packet with positionY only.

```

// Other players don't know about health change.

How can one overcome this issue then? sending the entire data is not always feasible.

# Answer
> 7 votes
Even though you are sending data using UDP, you will still need to add in your own form of reliability to handle situations like this. UDP just gives you the flexibility to do what you want, rather than deal with the reliable but less flexible format of TCP communication. Confirmation messages, or acknowledgement packets of a sort should be used when receipt of information is necessary, otherwise your client has no way of knowing if the data it sent needs to be resent. For instance, if you send critical information, and dont see a response within a set period of time confirming the receipt of that data, resend it.

# Answer
> 3 votes
You can also work around the problem by sending a full state update from the server to the clients, say every second. If a client did not receive a packet, it will behave incorrectly until it receives the full state update. Then it will be in sync again.

# Answer
> 3 votes
Many games use both UDP and TCP/IP for sending/receiving data and depending on how often the data is sent, different protocol is used.

For example:

UDP: positional updates, and anything else that could potentially be sent/received multiple times per second.

TCP/IP: inventory actions, spell/ability actions, (most user performed actions)

It really depends on the quantity of traffic of each item. If you find you are sending HP updates quite frequently then maybe they do need to be on UDP.

# Answer
> 2 votes
If you read the Quake 3 source code review, he explains the networking model which is very similar to your design, but with a solution for the dropped packets.

Essentially, in your model you are sending deltas against the directly previous state. In the quake3 model, you send deltas against the **last acknolwedged state** from the peer.

---
Tags: networking, multiplayer, state, udp
---


# Question
Title: Versions of GL and its device that don't display or required powers of 2 for the sprites
From **this question** aside from identifying possibilities of displaying images that don't needed to require powers of 2, what are the versions of GL that can actually display images even if don't needed the power of 2 size?

# Answer
> 1 votes
Here's your answer.

So it's been part of the core API since OpenGL 2.0, with a few hardware restrictions. As for OpenGL ES, check this answer.

---
Tags: opengl, textures, graphics, platform, multiple-graphics-devices
---


# Question
Title: How to keep Input System and Graphics System separate?
I want to keep Input System and Graphics System separate, but the Window Handler that's created by graphics component make everything really hard. How should I approach this situation?

# Answer
> 3 votes
Usually, you can't really separate window and input handling properly (when using events rather than polling the status).

IMO this is perfectly valid and not a part of bad design (reimplementing everything twice would be). I've just made a quick "sketch". It's been ages since I did UML, so might include mistakes - but it should get the idea across:

As you can see, the input/graphics handler is clearly separated and replaceable, while still depending on the same window implementation (e.g. a Win32 window with it's event handling).

Of course, the connection between these interfaces and the game systems could be completely different and not related to direct access or polling, e.g. there could be a message bus, global data fields, etc. but that's not really important here.

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


title: multi touch on HTML5 with JavaScript?

text:
# Question
Title: multi touch on HTML5 with JavaScript?
How action game controls should be implemented so that they would work on smart phones as well?

At the moment I use wasd/arrow keys and I am able to handle for example two keys down at the same time.

But many phones has no physical keyboard so should I render some control areas? Are there any JS libraries for this?

# Answer
The Akihabara framework provides special input areas for games when they run on multitouch-devices.
> 1 votes

# Answer
One way to go is to render on screen controls for mobile/touch devices. However, I feel like this isn't the best approach. In order to have the best possible experience for your game it should respond to touch events within the game itself. (Touch a unit to select it, touch & drag an item from slot to slot, etc)

Take Plants vs Zombies on iPad for example. One of the reasons why it's such a great game on that platform is that the gameplay itself meshes well with touch controls.

On screen controls are definitely the "easy way out" when trying to port your game to mobile touch environments but they feel clunky and probably won't give your users the best experience with your game.

Some games just aren't meant for touch interfaces and if a developer wants to support mobile/touch they're better off designing their game to accept that style of input from the start.
> 1 votes

# Answer
Take a good look at the Hammer framework, it's great:

http://eightmedia.github.io/hammer.js/

Here's a good an on-screen controller framework that looks pretty good too:

https://github.com/austinhallock/html5-virtual-game-controller
> 1 votes

---
Tags: iphone, input, javascript, html5
---


# Question
Title: To canvas, or not to canvas, when building browser-based games?
Background: I have extensive development background, but the last time I coded a game was many years ago. My Javascript skills are quite limited, and I intend to improve them by building a simple game — Tetris, Pac-man, or something of that complexity level.

Question: It seems to me that a fundamental choice I need to make is whether I should render on a `<canvas>` element or not.

With a canvas, I have basic tools for rendering points, lines, and more complex things on top of that. Presumably there are, or will be, also various frameworks to help with this.

Without a canvas, I could keep my objects in the DOM-tree, like a regular webpage, only quite complex, with many overlapping elements.

Is one approach better than the other? Are they mutually exclusive? How do I know which to pick?

# Answer
> 14 votes
Canvas and DOM aren't mutually exclusive, although they are fairly separate. One good approach would be to render the main game area (eg. the falling pieces in Tetris) using Canvas, and do all the UI (eg. score display) with DOM elements that are overlapping the canvas element.

That said, such an approach isn't really necessary for a primitive game like Tetris. Canvas is useful for more advanced graphical effects, but if those aren't required then sticking to DOM will give you wider compatibility; not all browsers support HTML5 Canvas.

# Answer
> 13 votes
**About DOM**
DOM works pretty well for old-school 2D, that means using no image rotation or scaling. There are actually tools for both of these jobs, but you can't count on them performing well.

For a game you should rely on the browser layout engine as little as possible, that means use `position:absolute` to place objects. Try as far as possible not to create and destroy DOM objects all the time, if you need a highly variable number of objects you may want a pool of idle DOM elements set to `display:none`, ready for being revived when needed.

**DOM vs canvas**
With the market share of IE8- shrinking canvas is becoming a more and more attractive option, for most games it's probably a fine choice. But for some jobs DOM is the easier tool to use, you can use some document flow if needed, you can catch clicks directly by the rendered object, it's easy to integrate scroll bars.

It's hard to cover the performance difference, it depends on the job and will vary wildly from browser to browser.

# Answer
> 6 votes
Completely depends on the type of game, although canvas fits "most" of them.

DOM management gets horrible at a certain point, the more elements you got the slower, the more elements you move around *THE EXTREMELY SLOWER.*

Managing asset loading order with IMG elements is... non-trival (intercept errors on purposely broken protocols on the image tags :D ).

Although, for games with mostly static imagery and low effect count I would still go with DOM though. Everything else, canvas is first choice (Point and clicking stuff, although hitmaps are a different story).

Canvas is so fast these days (even on iPhone), there's hardly any reason not to use it.

# Answer
> 3 votes
If you are making an HTML5 game, the canvas is by far better. Here's why:

1. Speed - Think of the canvas as an image. You draw to the image, and then it forgets what you drew. That dramatically increases performance, compared to DOM or SVG. What DOM and SVG applications do is they keep track of every object you place on the screen. That means if you have a large level with many objects on the screen, especially offscreen or hidden, those are drawn and kept track of anyways.
2. Drawing features - While DOM elements have powerful CSS3 transformations, that's nothing compared to the canvas's features. The canvas can draw any object, have powerful gradient support, plugins for displaying objects in 3D, filters, etc.
3. Support - When using the DOM, when you want to use experimental features like transformations or animations, you have to use the -moz-, -webkit-, -o-, and -ms- prefixes in CSS. In the canvas, you don't need to worry about that. Just draw with one function, and you're done. Another support related advantage of the canvas is how your application displays. As a website developer, the lack of DOM standardization between browsers drives me nuts. Backgrounds, gradients, transformations, etc. display differently between browsers, despite the detailed W3C specifications. In the canvas, I've only run across one thing that might be different - backgrounds. When displaying a tiled background, some browsers will take "tile-x" as center the tile at 0px on the x axis, and others take it as just tile the tile down.
4. Libraries and documentation - There are TONS of great libraries on documentations for making games with the canvas. Some libraries: CreateJS, paper.js, fabric.js, KineticJS, libCanvas, Processing.js, PlotKit, Rekapi, PhiloGL, InfoViz Toolkit, Frame-Engine, CAKE, Raphaeljs, Tweenjs, etc. I could list a ton more, but there's no point.

Down side - Animation - While there are many great libraries for animation, I love CSS3 animations. Their so easy to create, manipulate, and trigger. There are various hacks to make CSS3 animations work with objects with the canvas, but I suspect most people prefer not to use that method.

Good luck with your game, and I hope to see what you make!

# Answer
> 2 votes
If you consider targeting mobile browsers, in particular Android, and the game contains any moving graphics, avoid DOM animation. The stock browser in Android is useless, even though it's webkit. Check out this Android issue thread before you start: "Terrible rendering of CSS3 and Javascript animations in Browser and WebView".

Canvas in itself might not be any faster, but there are frameworks to invoke hardware acceleration for canvas animations, for example CocoonJS. There is a link to a video on the site, showing the performance gains you can achieve by using the framework (but I'm not allowed to post more than two links, for some reason).

# Answer
> 2 votes
Simple answer: WebGL with canvas fallback.

Nuanced answer: If your game has a lot of text, overlay an HTML text layer. Pixi.js is a battle-hardened display framework with some useful extras that works well for this.

# Answer
> 1 votes
Remember DOM stands for *document* object model. You will want to use it for making games only in very rare situations and prefer canvas in most cases.

Even if your game has small graphic requirements, doing it in DOM will have a bad performance; anything more than Tetris will probably run poorly.

I have a real world example: When I created an implementation of Conway's Game of Life, I started of with a 500x500 table, changing the background color of cells. In this version, a Glider was not running at more than 30 fps, bigger patterns resulted in hardly more than 1. In my canvas version of this game, it is now possible to run much bigger patters (population of 1000 and more) smoothly at ~30 fps.

Also, this should also be the case for SVG (Scalable *Vector* Graphics), although I never tried that in practice.

**Edit**: I have to admit that my example is not very good (because tables = bad). But the main point is still true: DOM manipulation is for documents. The browser has to lookup CSS and allocate more memory when you work on elements. It does not really make sense to be faster than canvas.

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


# Question
Title: Sponza scene with more physically motivated materials fit for physically based renderers
I've tried it with the default values and a lighting model copied straight from here, but the results were ludicrous. Basically since everything is way too shiny (high specular material values), most of the screen is very white unless I set the light intensity to a very small value or manually change roughness of the materials to very high values, in which case everything looks like someone spent years polishing the stuff.

Is there a version of the scene around with more physically motivated materials? Or am I just using them/interpreting them wrong?

The reason I even ask is because the scene seems to be very popular as testmaterial for global illumination algorithms, where physically based lighting seems to be commonplace.

# Answer
> 0 votes
Such a Sponza scene doesn't exist. Seems like all demos just use the basic Crytek Sponza model, some with the big flag in the middle removed.

---
Tags: sponza
---


title: How to get Components in ECS

text:
# Question
Title: How to get Components in ECS
I´m currently trying to develop a Game, which uses Component based Entities. The problem I\`m facing right now is how to mask my Components and retrieve them from the Entities. At the Moment i use a enumeration which has ab entry for each Component. Entities define then masks based on which Components they have associated. When I query for a Component i pass the correspoding enumeration value.

Here is a basic example to show how my Code works:

```
class Component
{
    public:
        enum Type
        {
            A       = (1u << 0),
            B       = (1u << 1)
        };
        virtual TypeBit() = 0;
};

class Entity
{
    public:
        shared_ptr<Component> GetComponent(Component::Type type);
        unsigned int TypeMask();
    private:
        std::list<shared_ptr<Component>> _components;
}

```

What I like i my approach is the simplicity of the Bitmasks with logic operations, i.e. to see if a System is interested in an Entity. The problem I have is, that, everytime when I add a new Component I have to add a new enumeration value. This adds potential for errors which is why I would prefer a more generic solution.

# Answer
You're going to run out of bits soon, too.

Try turning your Type into a CRC created from a descriptive string and instead of a list use a dictionary for \_components. That will remove the hard upper limit on types and maintain access speed. Also, no need to add new values all over the place which solves your immediate problem.

The long term view for the future is that with these strings and static factories you can later define your entities in a human friendly data file like XML (or even flat text files) and build entities at runtime from entries in that data file. Once you get deeper into coding you now have a basis for serialization and you can save and restore entire entities and their current state, but that's a really big task.

If you want to get fancy you can create a dictionary of strings to CRC to make runtime lookup cleaner and a reverse dictionary of CRC to string for debugging and human-friendly display.
> 0 votes

# Answer
I am using strings as component type identifiers, and dictionaries with the type string as key and the component as value. But I am using C# which enumerates the strings for faster dictionary access, so you might want to do that in c++ by yourself, or just use the string. Any way, your systems need to have a list of keys it accepts, and then compare the list to the entity component collection.
> 1 votes

---
Tags: entity-component
---


# Question
Title: Does passing uniform constants from technique into shader cause branches?
I am trying to find a way to organize my evergrowing number of shader techniques/functions (I am coding in sm\_3.0). One way is to do this:

```
float4 PS_Crossroads(PS_INPUT input, uniform bool left_right) : COLOR0
{
    if (left_right)
        GoLeft();
    else
        GoRight();
    ...
}

technique LEFT
{
    pass Pass1
    {
        VertexShader = compile vs_3_0 VertSh();
        PixelShader = compile ps_3_0 PS_Crossroads(true);
    }
}

technique RIGHT
{
    pass Pass1
    {
        VertexShader = compile vs_3_0 VertSh();
        PixelShader = compile ps_3_0 PS_Crossroads(false);
    }
}

```

My question is will this cause a branch at runtime or will the compiler be smart enough to split it into two separate techniques?

Thanks.

**P.S. Ok I won't post this as answer, because we already have an answer by someone much more experienced than me, but from my humble tests (on different PCs) and my humble Google research, this approach (using uniform constants) is efficient and indeed forces the compiler to create different shader versions for each branch, removing flow controll completely from the finall compiled shader. I tested the compiled shader codes with Nvidia NSight.**

# Answer
In HLSL, creating separate techniques that pass different compile-time values into a shader function will definitely generate efficient code. Optimizing away control flow due to compile-time constants is implemented in Microsoft's HLSL bytecode compiler, which means it doesn't matter which GPU or drivers you have; the optimization is already done by the time the shader gets to the driver's shader compiler. (Unless you disable optimization in the HLSL compiler - in which case, the optimization may very well still be done at the driver level.)

In GLSL, where there is no IHV-independent compiler and bytecode language, things are less certain. Shader compilers are generally pretty aggressive about optimizing away compile-time constants in any form, and a good mature GLSL compiler will have no trouble with this. But there are some platforms/drivers where the GLSL compiler doesn't do a good job, which led Unity developer Aras Pranckevičius to develop a standalone GLSL optimizer.
> 2 votes

# Answer
### You can't be sure

Well, depending on the compiler and the GPU, because uniform variables only change per pass the GPU will more likely always take that branch for each pass, but unless you use a profiler you will never know and can't be sure for every driver/GPU.

\[Edit\]Based on Nathan Reed comment, the HLSL compiler will optimize constant uniforms because its optimization can happen at Microsoft front-end compiler, before being passed to the GPU driver compiler. Though this is not the always case with GLSL.

### Alternative technique

But anyway people don't usually organize shaders this way. My recommendation is to use **compile time tokens and do conditional compilations**, where you have one big shader that calculates different things, then you compile different versions of it, without rewriting it, this way you will be 100% sure there is no branching overhead. This technique is also called uber-shader which is covered in this answer.
> 3 votes

# Answer
This is not required by the specification, but most public drivers do implement this in some fashion.

The only way to be sure your specific shader is optimised this way is, unfortunately, profiling.

See also: https://stackoverflow.com/questions/4176247/shader-branching-question for more information on such branching.
> 0 votes

---
Tags: xna, hlsl, shadermodel3
---


# Question
Title: glRotatef rotation never applied to 3d cube
I have a floating cube that I want to rotate around the Y axis. The cube renders fine, the proper size, the proper coordinate, the proper texture/faces, etc.

However, the rotation is never applied. My update logic calculates a new `rotation` value, between `0` and `360`.

```
// Set the coordinates, rotate Y axis
GL11.glTranslatef(x,y,z);
GL11.glRotatef(rotation, 0, 1f, 0);

// Each cube face rendered, etc...
GL11.glColor3f( //...
GL11.glTexCoord2f(//..
GL11.glVertex3f//..

```

No matter what combination I've tried, the cube never changes it's rotation.

**Update** Per a comment, I was using glBegin outside the glRotatef and the comment advised that I use glPush/Pop:

```
GL11.glPushMatrix();
    GL11.glTranslatef(x,adjY,z);
    GL11.glRotatef(rotation, 0f, 1f, 0);
GL11.glPopMatrix();

GL11.glBegin(GL11.GL_QUADS);
block.renderVertex(x,adjY,z,1,null,0.1f);
GL11.glEnd();

```

# Answer
Your problem is the placement of your glPopMatrix call. The current matrix on the stack only affects drawn objects while it is current, but you're drawing after you pop the matrix.

The correct order is:

* glPushMatrix to go to a new current matrix on the stack.
* Apply transforms (translate/rotate).
* Draw objects.
* glPopMatrix to restore the previous matrix.

Do you see why this is? If not, I'd advise you to review some documentation about how the GL matrix stack works.
> 1 votes

---
Tags: opengl, java
---


# Question
Title: Particle system lifetimes in OpenGL ES 2
I don't know how to work with my particle's lifetimes. My design is simple: each particle has a position, a speed and a lifetime. At each frame, each particle should update its position like this:

```
position.y = position.y + INCREMENT * speed.y

```

However, I'm having difficulties in choosing my `INCREMENT`. If I set it to some sort of `FRAME_COUNT`, it looks fine until `FRAME_COUNT` has to be set back to 0. The effect will be that all particles start over at the same time, which I don't want to happen. I want my particles sort of live "independent" of each other.

That's the reason I need a lifetime, but I don't know how to make use of it. I added a lifetime for each particle in the particle buffer, but I also need an individual increment that's updated on each frame, so that when `PARTICLE_INCREMENT = PARTICLE_LIFETIME`, each increment goes back to 0.

How can I achieve something like that?

# Answer
Are you attempting to implement a stateless particle system in a shader? You need an extra vertex attribute: timeoffset. Pick a random timeoffset value for each particle.

So your vertex attributes are:

```
startpos // vec per vertex
velocity // vec per vertex
timeoffset // scalar per vertex (N random values in [0..lifetime])

```

and you have the uniform variables:

```
currenttime. // scalar, one value for all vertices
lifetime. // scalar, one value for all vertices

```

Then in your shader:

```
t = currenttime + timeoffset;
t = t % lifetime;
pos = startpos + t * velocity;

```
> 0 votes

---
Tags: opengl-es2, particles
---


# Question
Title: What is the standard way to synchronize sound effects with sprite animations?
Let's take a situation where you have an RPG with spells and each spell animations have a different number of frames and they have very different requirements for sound effects. Let's assume that each spell has only 1 continuous animation associated with it (as opposed to multiple modular pieces that are used to form a full animation) ala the old 16 Bit Final Fantasy games.

The only way I can think of in order to make sure that the sounds and animations sync up is to:

* Get the number of frames of an animation.
* Get the time between each frame of the animation. (if it's 30 fps then it's 1/30th of a second per frame.)
* Then create a sound file that is exactly the same length as the animation.

So this means that if an animation is 5 seconds long, running at 30 fps, with a total of 150 frames, the sound file will also be 5 seconds long. If the animation should have an "impact" sound on the 30th frame, that means the sound file will include the sound of impact at the 1.0 second mark.

At the end, we start the animation and the sound effect at exactly the same time and hope that the frames and the sound sync up.

This sounds like it could pose problems when frames are skipped or something happens during the animation and the sound gets played slightly too soon or too late, and will cause the sound and the animation to go out of synch. Is this the best approach or are there usually a better way that I'm just not seeing?

The answer doesn't necessarily need to be for Cocos2D specifically if it's conceptual, but if there's a specific solution for cocos2d, I'd love to hear it.

EDIT: I just also realize that with this method, if we happen to go in and adjust the number of frames or timing of the animation later, we MUST also go back and change the sound file. This sounds like a terrible cause for human error (forgetting to update sound files after animation change.) I hope there are better methods out there.

# Answer
Do it via events.

Spell begin is an *event*. Start playing the sound for that event.

Enemy getting hit by spell is also an event. If the enemy is further away and you Throw a dart, for example, you only play the second sound (dart hitting) once the dart reaches the target (if you consider Throw as a spell).

If you need to tie it to a *frame* (so for example, play the "explode" sound 30 frames from now *regardless of real-time frame rates*)), the easiest way to do so is using *callbacks*. Callbacks are just "blocks of code you schedule to run in the future". Here is an example of my callback creation setter:

```
- (void) addCallback:(Callback*)callback inHowManyTicks:(unsigned long long)execTicksIntoTheFuture
{
  callbacks.push_back( new TimedCallback( tick + execTicksIntoTheFuture, callback ) ) ;
}

```

A `TimedCallback` is just a wrapper around a `std::function` (or you could use an Objective-C `^{block}`. The `std::function` is executed when its frame is up.

Another way (less global) is to include *events in your animation*. So, if you need to play specific sounds on specific animation frames a lot, then store a `map<int,Sound*>` in the `Animation` class. On each frame of the animation, check if there is a corresponding `Sound*` to play for that Frame.

You could also store a `map<int, std::function>`, in the `Animation` object, which would allow you to callback a `function` during the animation.
> 6 votes

# Answer
The way i do it is make custom event listeners for my animation class and have them control my sound. so if my animation has started callback.start(); and start my sound in that method. if my animation was paused do callback.pause(); and pause the sound. when the animation has ended you callback.end(); and have the sound end as well.

but for perfect synchronization i would go as far as counting sound frames and sleeping(pausing) my sound if it gets to far a head and do the same for my animation.

I have never had to do that until this day because the first suggestion satisfies my needs just fine for now.
> 1 votes

---
Tags: animation, cocos2d, sound, audio, sound-effects
---


title: Whac-A-Mole like

text:
# Question
Title: Whac-A-Mole like
am trying to make a game that have a "whac-A-Mole" game principle

The problem that am facing is that i don't want the "enemies" to get out from holes at the same time, not even in a different close times, so i want to keep a minimum interval between each enemy and in the same time i want too keep the feeling of randomization, currently am making it like this :

```
enemy[0].hidingTime = Random.Range (hidingTimeRangeMin, hidingTimeRangeMax);
            for (int i =1; i < NumOfEnemies; i++) {

                    enemy[i].hidingTime = enemy[i - 1].hidingTime + Random.Range (1, 3);
            }

```

this fixed the 1st problem, but it will always make the enemies come out in the same order (1st one is faster, and last one is the last to come) i hope i explained it right thank you and have a great day

# Answer
> 1 votes
Enemies coming out in order is only a problem if enemies aren't identical. If there are some unique enemies, maybe shuffle the enemies first (applying any heuristics about increasing enemy level) and then apply your algorithm. For fairness you could also tweak the random range depending upon the distance from the last enemy, e.g. it takes longer to move the mouse 3 holes than 1.

---
Tags: random
---


# Question
Title: What are the differences betwen Texture, TextureRegion, TextureAtlas, Sprite and Image in libgdx?
I've searched around for tutorials. I've seen people using the above classes to load images.

As according to my understanding, all of the classes can read in a non-power of two images, TextureRegion/TextureAtlas are usually used to load sprite sheet, in which the sheet contains multiple images. While for Texture/Sprite/Image, they are used to load a sprite sheet with single image.

However, I'm not so sure in which situation I should use Texture/Sprite/Image and in which situation I should use TextureRegion/TextureAtals.

Please correct me if I'm wrong, as I'm a bit confused by the terminologies in the API after looking various tutorials.

# Answer
> 22 votes
First, Texture vs TextureRegion: When you do something like Texture t = new Texture(path), you are loading that into GPU. In addition, you should load power of 2 textures. You could work with other resolutions (Texture.setEnforcePotImages = false), but it's encouraged to use pow of 2.

Now, TextureRegion, takes a "piece" from a Texture, no matter it's dimension. The advantage of having one Texture and multiple TextureRegion of that Texture, is that you are NOT loading every region into GPU.

As you may be thinking, when you want to draw with the SpriteBatch, it's much more efficient to use TextureRegion instead of multiple Textures, I'm sorry my english is not good enough. Here is a good explanation: Textures TextureRegion & SpriteBatch

---

Now, you want to use TextureRegion and one single image in power of 2 resolution with all the spritesheets and images. Do you have to create TextureRegions with all the coordinates and dimensions? Do you need to open paint to count pixels? Noooo, you don't. You can use something like TexturePacker. It will pack every texture into one image AND create a .pack file with de dimensions and coordinates of all of them.

The result will be something like this:

Instead of creating a Texture, create a TextureAtlas, like this:

Now, creating your TextureRegions would be as simple as:

(Note that the name of the region is the name of the original image without the extension).

---

Sprite holds the geometry, color, and texture information for drawing 2D sprites using Batch. This mean, you can easily rotate them and move. I've created my own Entity class, and I don't need Sprite class. You would probably do the same. I don't find this class really usefull.

---

Image class inherits from Actor. This mean you can add it into a stage. It's part of the Scene2D package. If your are new to libgdx, and you don't know about this package, this is enough information for you about this class. It's a really interesting topic, but not to answer in this question.

Hope it helps :)

---
Tags: libgdx
---


# Question
Title: Allowing a player to walk up and down slopes without resistance
I am trying to implement a platformer where both the player and the level are made up of arbitary polygons. One requirement is that the player can stand still on slopes, and walk up and down them freely without resistance.

For collision detection, I have been using the Separating Axis Theorem (SAT) to calculate overlap between the player and environment. The problem is with the resolution phase. The SAT gives the axis of minimum overlap and the amount you need to move an object along the normal in order to resolve this overlap. This method leads to the player sliding downwards when gravity is applied on a slope, or encountering resistance when moving horizontally into a slope.

To solve this, I want to resolve the collision by applying the minimum y-offset:

And an answer to a similar question here seems to provide some of the ground work of how to do it, but I don't feel I have all the information I need. How would such a method work for arbitary polygons? From which point do I need to be calculating the overlap from? Do I have all the information I need already from calculating the separating axis or do I need to compute further values?

# Answer
> 4 votes
The minimum y offset can be calculated with the minimum overlap:

The blue line is the MTV from the SAT algorithm, the red line is the minimum Y offset.

```
phy::vect2D c =  phy::_poly_collision(p1,p2);

if(c.y != 0 && c.x != 0) {
    p1.y_pos += ((c.x*c.x) / c.y) + c.y;
} else {
    p1.x_pos += c.x;
    p1.y_pos += c.y;
}

```

# Answer
> 1 votes
Your collision detection should be performed during each frame before the actual displacement takes place. Knowing how much you are displacing in each axis, allows you to calculate your overlap based on how far off the collision was. For instance, if your character falls 10 units due to gravity, but a collision occurs 5 units away, there is a 5 unit overlap that you need to compensate for.

Additionally, when I recently wrote character physics for an object, I broke down the collision tests into vertical and horizontal tests. I first checked and compensated for horizontal collisions, and afterwards vertical. This provided the correct movement behavior I desired.

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


title: Lag created when detecting collision

text:
# Question
Title: Lag created when detecting collision
I'm fairly new to gamedev and have encountered a problem with the collision detection system.

The collision is essentially worked out like this:

```
for (int x = 0; x < playerprojectiles.Count; x++)
        {

            for (int i = 0; i < enemyships.Count; i++)
            {
                Vector2 projectilepos = new Vector2(playerprojectiles[x].position.X, playerprojectiles[x].position.Y);
                Vector2 enemypos = new Vector2(enemyships[i].position.X, enemyships[i].position.Y);

                Console.WriteLine("I=" + i + "  ,  " + "x=" + x);
                if (Vector2.Distance(enemypos, projectilepos) < 20)
                {
                    playerprojectiles.RemoveAt(x);
                    x--;
                    break;
                }

            }

        }

```

I can see the problem; it is having to iterate through too many items. However, I can't think of a way to overcome this.

Any help? To specify, can someone direct me to a method that would allow me to detect collision without impeding performance so severely.

# Answer
The usual solution in order to avoid checking for every pair, would be to implement some kind of spatial partitioning like quad tree or bsp tree.

but this might be too complex for your simple game. There are other trivial optimzations you can do in your loop:

* Calculate DistanceSqaured instead of Distance, because distance needs to calculate square root so distance squared could be much faster, but you need to check with squared distance so instead of 20 you need to compare with 400.

`if (Vector2.DistanceSquared(enemypos, projectilepos) < 400)`
* You can divide the game into regions (like a grid) and check the projectile with enemy ships in the same region only. This is simpler than a quad tree.
* As an alternative you can sort your enemy objects position by Axis, for example sort by X then by Y. And do collision detection based on near objects, for example projectile coming from -X is more likely to hit objects with less X coordinates.
* Also you can get rid of temporaries by not copying your variables every time to other variables. As suggested by MickLH.
> 1 votes

# Answer
If you have too much objects, divide the regions. In 3D this is called Octree. You can divide your region in 4 regions and calculate the region of the items. Then you only have to check the items in the same region as the projectile. And when it's not enough, divide this region again. The problem is that you have to calculate, in what region the item is. So maybe you need longer to calculate the regions -\> you have to figure out what division is the best.

Another thing is maybe the usage of Lists. I've read somewhere that an array is much more faster than a list. Try to use arrays. But i don't know if it's faster in this case, because you have to check the whole array every call...

Maybe this also helps: Quad trees/grid based collision - putting logic into action
> 0 votes

# Answer
A simple answer could be a simplified axis sweep broadphase.

This involves sorting your list of "enemyships" (the larger list that changes less) by some coordinate, and then taking an early out when you know it's impossible to collide.

The cost of the sort should be almost free since it only has to do work when new enemy ships are added.

It might look like this (UNTESTED):

```
int firstErase = -1, lastErase = -2;

// Sort all your ships from left to right (not sure if this is the right order)
enemyships.Sort(delegate(EnemyShip a, EnemyShip b) {
    return a.position.X - b.position.X;
});

for (int x = 0; x < playerprojectiles.Count; x++) {
    //left as an exercise for the reader:
    //start from the middle and only check the logical half

    for (int i = 0; i < enemyships.Count; i++) {
        // this is a slowdown: Console.WriteLine("I=" + i + "  ,  " + "x=" + x);

        // early out for everything too far right to be possible
        float DistanceX = enemyships[i].position.X - playerprojectiles[x].position.X;
        if (DistanceX > 20) break;

        // just do DistanceSquared() manually since we did part already
        float DistanceY = enemyships[i].position.Y - playerprojectiles[x].position.Y;

        if (DistanceX*DistanceX + DistanceY*DistanceY < 20*20) {
            // dont edit the list you are looping through
            playerprojectiles[x].eraseMe = true;

            //Maybe this should go here too:
            //enemyships[i].DoDamage(playerprojectiles[x].damage);
            break;
        }
    }
}

int c = playerprojectiles.Count;
while (c--) {
    if (playerprojectiles[c].eraseMe) {
        playerprojectiles.RemoveAt(c);
    }
}

```
> 0 votes

---
Tags: xna, collision-detection, lag
---


# Question
Title: What are "distance fields" and how are they applicable to collision detection?
I was looking at some efficient methods for collision detection in a scene with both static and dynamic objects when I came across "distance fields."

I tried to search and understand this concept, but I could only find papers written in very complex language. Can someone explain in easy words what distance fields are and how can they be used for collision detection?

# Answer
A distance field (or distance transform or distance map) is a gridded structure where each cell in the grid represents the shortest distance from *that* cell to a cell with some other property. Most often that "other property" is a boundary type of cell, such as a wall that a player cannot pass, or the surface of a mesh.

Distance fields have a lot of applicability. You could imagine, for example, how they might be used to implement movement guidance (by creating distance maps to either dangerous or desirable objects and weighting movement decisions by them).

However, you specifically asked about collision. Using distance fields to perform collision detection between two moving objects can quickly become rather inefficient, as rebuilding distance fields can become very slow as the scope of the field grows (especially in 3D, although methods for improving generation time are an area of research).

Distance field collision is thus used mainly to detect collision of a dynamic object with a static one. Most frequently, I've seen this done for detecting collision of cloth (or other deformable) objects with other, fixed objects in the scene.

Crudely, this is accomplished by using a *signed* distance field for the static object where one sign (often negative) represents a cell *inside* the mesh and a the other (obviously often positive) represents a cell outside the mesh. The cloth mesh's particles can be transformed into the local space of the static mesh, and the "before" and "after" positions of a particle during a given cloth simulation step can be checked against the distance field to determine if the sign changed (and thus a collision occurred). This is the method discussed in this 2003 paper on cloth simulation, for example.

Note that I wouldn't suggest using distance fields as your only collision detection method. They can be fairly efficient for what they are good at, but they are not good at everything. The best way to achieve efficient collision detection is frequently to use multiple methods, hierarchically, with increasing precision as you traverse down the hierarchy.
> 14 votes

# Answer
> What are distance fields ?

In geometry and computer graphics and also used in image processing, a distance field (in simple words), is a label on each cell (pixel in image processing) with the distance of the nearest polygonal object or a pixel with special properties in image processing.

In other words it's a label for each cell that has a value of a nearest object with special property defined by the map. The object vary depending on the application.

The above image contains a Distance map for boundary pixels. Notice how each pixel contains the distance to the nearest boundary pixel. The distance is calculated using Manhattan distance.

There are different ways to calculate the distance, typical approaches include:

> How is it applicable in collision detection ?

By maintaining a distance map for objects in the scene, you can check if two objects are colliding based on there distance. Unfortunately maintaining such map is expensive. And this is usually used in self intersecting objects like cloth simulations were distance maps can be maintained and updated more efficiently because of the nature of the object.
> 6 votes

---
Tags: collision-detection
---


# Question
Title: Does a patch of simplex noise sum up to zero?
Just for interest, when sampling simplex noise in any given dimension, would the sum of all samples run towards zero?

# Answer
No, the sum will not converge (run towards zero). It may pass by zero, or be zero at some point, but there's nothing that would make the sum get closer to zero. The sum along any given dimension will be random. However, a sample of sums will tend toward a normal distribution.
> 6 votes

---
Tags: statistics, mathematics, simplex-noise
---


title: glGenerateMipmap confusion

text:
# Question
Title: glGenerateMipmap confusion
I'm trying to get a grip on mipmaps with OpenGL. I believe I understand the concept, but when trying to have OpenGL generate them I wonder how it determines how many mipmaps to generate?

Here's what I'm running with right now to initialize a 2d texture:

```
    glGenTextures(1, &mTexture);
    glBindTexture(GL_TEXTURE_2D, mTexture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA , textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, &textureData[0]);
    glGenerateMipmap(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, 0);

```

Nowhere do I specify how many mipmap levels to generate. How many mipmaps are generated in this case? Where do you specify this number?

I've also seen another technique from http://www.opengl.org/wiki/Common\_Mistakes where you use `glTexStorage2D` to specify all the mipmaps levels instead - but how many levels can you specify and what is a reasonable number for quality?

# Answer
> 2 votes
The number of mip map levels on a texture is defined by the range between GL\_TEXTURE\_BASE\_LEVEL (default 0) and GL\_TEXTURE\_MAX\_LEVEL (default 1000). You can set these manually via glTexParameteri or via glTextureStorage. In case of glTextureStorage the min level will be 0 and the max level will be whatever you hand over as a parameter to glTextureStorage - 1.

glGenerateMipmap populates the entire range (in this case 1000 textures). Obviously after the generated mipmap texture reaches a certain size (e.g. 2x2, I'm not sure what the standardized minimum size is) all mip map levels after it will use the same texture. I'm not sure if space is actually allocated for those extra textures or if they just refer to the same texture somehow (probably implementation dependent).

If you want to avoid that overhead and make sure, set GL\_TEXTURE\_MAX\_LEVEL to log\_2(n) where n is max(texture\_resolution\_x,texture\_resolution\_y) since that is the maximum amount of levels required before the textures gets to a size of 1x1 pixels.

---
Tags: opengl, c++, textures, mipmaps
---


# Question
Title: Center directional light shadow to the cameras eye
I'm currently drawing my directional light shadow using this view and projection:

```
XMFLOAT3 dir((float)pitch, (float)yaw, (float)roll);
XMFLOAT3 center(0.0f, 0.0f, 0.0f);

XMVECTOR lightDir = XMLoadFloat3(&dir);
XMVECTOR lightPos = radius * lightDir;
XMVECTOR targetPos = XMLoadFloat3(&center);
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

XMMATRIX V = XMMatrixLookAtLH(lightPos, targetPos, up); // This is the view

// Transform bounding sphere to light space.
XMFLOAT3 sphereCenterLS;
XMStoreFloat3(&sphereCenterLS, XMVector3TransformCoord(targetPos, V));

// Ortho frustum in light space encloses scene.
float l = sphereCenterLS.x - radius;
float b = sphereCenterLS.y - radius;
float n = sphereCenterLS.z - radius;
float r = sphereCenterLS.x + radius;
float t = sphereCenterLS.y + radius;
float f = sphereCenterLS.z + radius;
XMMATRIX P = XMMatrixOrthographicOffCenterLH(l, r, b, t, n, f); // This is the projection

```

Which works prefect if the center of my scene is at `0.0, 0.0, 0.0`. What I would like to do is move the center of the scene relative to the cameras position. How can I do that?

# Answer
> 1 votes
```
XMFLOAT3 dir((float)pitch, (float)yaw, (float)roll);
XMVECTOR center = XMVectorSet(eye(0), eye(1), eye(2), 0.0); // Se the center to the eye

XMVECTOR lightDir = XMLoadFloat3(&dir);
XMVECTOR lightPos = (radius * lightDir) + center; // Add the center
XMVECTOR targetPos = center;
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

XMMATRIX V = XMMatrixLookAtLH(lightPos, targetPos, up);

// Transform bounding sphere to light space.
XMFLOAT3 sphereCenterLS;
XMStoreFloat3(&sphereCenterLS, XMVector3TransformCoord(targetPos, V));

// Ortho frustum in light space encloses scene.
float l = sphereCenterLS.x - radius;
float b = sphereCenterLS.y - radius;
float n = sphereCenterLS.z - radius;
float r = sphereCenterLS.x + radius;
float t = sphereCenterLS.y + radius;
float f = sphereCenterLS.z + radius;
XMMATRIX P = XMMatrixOrthographicOffCenterLH(l, r, b, t, n, f);

```

---
Tags: c++, directx, shadows, shadow-mapping, lighting
---


# Question
Title: Finding a specific point in a graphic model in code
I'm not really sure what I'm asking, so sorry for the bad title. I'm still new to game programming and especially the "game specific parts" like models and graphics.

Let's say I have a model of a space ship. On this model there's are a couple of locations where I want to place thrusters and there's another spot for a large main thruster. I think I have most of the physics figured out. I can place thrusters at positions relative to the center of mass and the ship behaves appropriately when they're fired. Now, back to the model - how do I place my engines (in the simulation), how to get the relative X, Y and Z values from the model?

Obviously, the naive solution would be to open up the model in a modelling program and find the coordinate where I want the engines to be placed and then put those values in my database. That would mean that every time I change the model or create a new ship I'd need to redo this procedure and handle a lot of values. Surely this can't be how it's done? Is there a way to "mark" a point in a model and find that point from code? Am I missing something obvious?

I'm using C# and XNA, by the way.

# Answer
> 1 votes
I've done this by creating a special object or vertex at the point of interest and naming it something special. Then when the model is being loaded, those points of interest are loaded as well. For example, in Blender you can create an empty object that has its position exported along with all the other model data.

How you create the point of interest and how you read it in will depend on the technology you're using.

This solves the problem of keeping the point updated when the model changes, since you simply move the point at the same time you're updating the model. While not fully automatic, it's a simple approach and keeps the changes you make localized to one task.

# Answer
> 2 votes
If you're using skeletal animation on your ship, one way to do this is to create joints (bones) representing the attachment points. These joints wouldn't have any geometry attached to them, but would just serve as position (and/or direction) markers. You could give them special names that would allow you to look them up from the game engine.

If you don't already plan to use skeletal animation, it's probably not worth implementing just for this. However, you can still do something similar by creating a specially-named object in your modeling program (it could be just a cube, or you could model a little arrow or something to indicate thrust). At runtime, when you load this object you would throw away its geometry and just use its position as the marker.

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


title: Making money with engines?

text:
# Question
Title: Making money with engines?
As the title says.

Making money with games, especially free to play ones, is a well-known topic that‘s often discussed. So one can either sell the game, fill it with ads, get a sponsorship, find a publisher, etc etc...

What i wanted to ask is: is possible to make money out of game engines? I know it‘s just a matter of polishing it and then publishing it (like Unity and other engines did), but are there any other way of making money if you‘re a developer writing an engine ( a good one with potential, not just a little one-use framework)?

# Answer
> 2 votes
Yes, it's possible. But, just like making money with games (or anything else), it's not trivial. Like similar products, there's a number of basic ways to generate an income. The methods in the list below come in many forms, but the most basic of those forms are:

* **Direct sales**. Sell the engine for developers to use.
* **Advertising**. Generate income from ads placed on the site where the product is downloaded from.
* **Royalties**. License the engine to developers for a share of their revenue.
* **Donations**. Ask for donations on the site.
* **Various combinations of the above.**

# Answer
> 1 votes
Byte56 already listed the most popular ways to monetize a game engine. I just like to add some maybe less common though interesting ways.

* **Free and pro version**. Provide a kit with limited features for free so that it becomes popular and potential costumers can try out the workflow. Then, take money for the advanced version. For example Unity does exactly that.
* **Offering paid support**. Do what Red Hat does with Linux. Give away the engine for free and get money from services around like maintenance or support. Would be even interesting to provide developer workforce, but this is another topic. (They would already now the engine well.)
* **Find investors**. Even though individual angles would be great, this seems too unlikely to me. Anyhow, crows founding become very popular in the gaming branche in the last year. Take a look at Kickstarter. For now, I haven't heard of bare engines founded there, but this could work, too.
* **In game advertising**. This is very experimental but a innovative way that might have potential. You could add ad in game banners but that would disturb users and is not what I am talking about. Instead, I can think of two way for placing ads in a game that wouldn't bother users too much. First, on loading screens where the player needs to wait anyhow. Second, inside the scene, say, at advertising pillars, but stops, and so on. That would even make the games more realistic.

I hope this helps as an addition to the other answer already posted. Personally, I see the last point promising for the feature and would like to know if someone tries to use this form of monetizing in a game engine or game.

---
Tags: business
---


title: Tangent on generated sphere

text:
# Question
Title: Tangent on generated sphere
I have difficulties understanding the tangent/bitangent concept for normal mapping, or rather the calculations of them.

I draw a sphere which is generated with the code in the OpenGL redbook http://www.glprogramming.com/red/chapter05.html. I use cube mapping to texture the sphere.

Now, pretty much everything in the web links to http://www.terathon.com/code/tangent.html. But in that algorithm, they use the texture coords u and v, which I don't have like this because my texture mapping is 3D...

Any pointers to how I can compute the tangents and bitangents with this setup?

Also, aren't the tangents just vectors orthogonal to the normal of a point on the sphere? To me it seems there could be an easier way..

Edit: As far as I understand I need those values to be able to "apply" the normal from the normal map to the point on the sphere. (I'm not sure what the correct mathematical terminologies are here). In other words, to deviate the normals of any point on the sphere based on the normal map. I calculated the normals as point\_on\_surface - center\_of\_sphere (which, in modelspace, when the center is (0,0,0), is just point\_on\_surface)

# Answer
> 0 votes
Using a cubemap lookup into a tangent-space normal map is a bit tricky, since two neighbouring pixels rendered from the same primitive might be looking up from different cube map faces, with different tangent directions.

A simple way to solve this is to ensure your sphere geometry is split exactly on the lines corresponding to the edges of the cubemap (say, by taking a subdivided cube and normalizing all the vertex positions to bend it into a ball - something like this).

Once you've done that, you can lay out your cube map faces as a flat 2D texture, and map into it with regular UV mapping instead of cube map lookups, if you prefer. Your exporter should be able to generate usable tangents for this version automatically.

This is probably the most reliable way to get a consistent mapping between your normal map generation and rendering.

If that's not an option, then you may need to compute your tangent vector in the fragment shader, so it can handle cubemap face discontinuities (and thus, potential tangent discontinuities) within a single primitive. The math here gets a bit tricky if you want to remove all visible pucker where cubemap faces meet, so I don't recommend it.

Here's a first stab at the problem...

(For the following, I'm assuming a left-handed coordinate system with y+ pointing up/north. I assume that the non-polar cubemap faces expect the tangent to point "east," with the texture's "up" pointing to z+ for the north pole face and z- for the south pole. You may need to flip some signs if this doesn't match your setup.)

First, determine which cube map face the current fragment belongs to by finding which component (x, y, z) of its normal is furthest from zero.

* If x: your tangent is sign(normal.x) * normalize(cross(normal, cross((0, 0, +1), normal))
* If y: your tangent is normalize(cross(normal, cross((+1, 0, 0), normal))
* If z: your tangent is sign(normal.z) * normalize(cross(normal, cross((-1, 0, 0), normal))

(In each case, the tangent points along the perimeter of a great circle running through the current pixel and the center of one of the neighbouring cubemap faces)

Note that the v direction of a cubemap face isn't perpendicular to the u direction at the corners of the cubemap when projected onto a sphere (they meet at a 120 degree angle), so if that causes visible artifacts you'll need to compute a non-perpendicular bitangent too, using equations similar to the above.

I hope that's of some use!

# Answer
> 1 votes
In principle, you can use any method of generating tangents and bitangents that you like, as long as the method is consistent between the process generating the normal map, and the process applying it.

Usually, we use tangents and bitangents that match up with the texture UV axes because that gives the colors of normal maps a simple interpretation - red controls the left-right deflection (relative to the texture) and green controls the up-down deflection. It also allows the same normal map to be reused on many surfaces with different orientations in 3D, or different UV mappings.

Your normal map plugin presumably assumes this is the case. When generating a normal map from a 2D map of the earth, it creates a red channel that represents left-right deflection relative to the texture, and a green channel that represents up-down deflection.

So, to apply this normal map correctly you would need to create tangents and bitangents that correctly represent what "left", "right", "up", "down" in texture space correspond to in 3D space. The simplest way to do this is to create a UV mapping that correctly applies the original 2D map to the sphere (e.g. using a Mercator projection, or whatever the original projection of the map was), then generate the tangents and bitangents from the UV mapping in the usual way.

---
Tags: opengl, normal-mapping, sphere
---


title: LWJGL Collision Detection

text:
# Question
Title: LWJGL Collision Detection
I cannot find LWJGL collision detection with a camera and walls. Like making it to where you can not walk through walls and other different shaped rectangular prisms and cubes. How do I set up LWJGL collision?

# Answer
LWJGL does not have a physics library built in to it. If you want to add collision detection to LWJGL, you'll need to create the collision detection yourself or use an existing library to add physics and collision detection to your game.
> 1 votes

---
Tags: collision-detection, lwjgl
---


# Question
Title: Algorithm to find all tiles within a given radius on staggered isometric map
Given staggered isometric map and a start tile what would be the best way to get all surrounding tiles within given radius(middle to middle)?

I can get all neighbours of a given tile and distance between each of them without any problems but I'm not sure what path to take after that. This feature will be used quite often (along with A\*) so I'd like to avoid unecessary calculations.

If it makes any difference I'm using XNA and each tile is 64x32 pixels.

# Answer
> 11 votes
I think this might be easier with a visual aide. Here are some different things we might mean when we ask for "tiles within a given radius"

From the OP's responses above, it sounds like the top-left version is desired (Euclidean - screen space). That seems to have generated a bit of confusion since most tile-based games consider ranges in tile space.

No matter which metric you use, a useful strategy is to limit your search area.

You can take advantage of the fact that in all of these metrics, the desired tiles occur in runs with no gaps in the middle (unless your tiles are sparse). I'll assume your tiles are densely packed in rows & columns (either screen-aligned or tile axis-aligned - it changes the details but not the main idea).

1. Determine the least row that could possibly overlap your radius.
2. Determine the greatest row that could possibly overlap your radius.
3. For each row in that range, determine the least & greatest columns that could possibly overlap your radius.
4. Return all tiles within these bounds.

As an example, I'm going to use the tile space Euclidean metric (top right), for simplicity.

```
for(row = ceil(sourceRow - radius) to floor(sourceRow + radius))
{
  rowDifference = row - sourceRow
  columnRange = sqrt(radius * radius - rowDifference * rowDifference)

  for(column = ceil(sourceColumn - columnRange) to floor(sourceColumn + columnRange))
  {
     yield GetTile(row, column)
  }
}

```

(Please excuse the sloppy pseudocode and lack of bounds-checking to ensure we're within the map bounds - those should be easy to add)

This version does only O(radius) distance calculations (linear in the radius, rather than quadratic as with methods that test every tile in a neighbourhood, or the brute force O(n^2) which tests every tile on the map)

If that's not directly applicable, it shouldn't be hard to adapt the basic strategy to a different metric/tile arrangement.

# Answer
> 0 votes
Just expand outward from the origin tile:

```
find(radius, origin, cell, solution) ->
    solution.append(cell)
    for n in cell.neighbors - solution
        find(radius, origin, n, solution) if dist(origin, n) <= radius

```

Then just pass in the origin tile as both origin and cell on the original call:

```
cells = []
find(radius, origin, origin, cells)

```

This also encapsulates away your distance function to use whichever metric you like. Note that `cell.neighbors - solution` is the set of all cells in `cell.neighbors` that aren't in `solution`.

---
Tags: xna, isometric
---


# Question
Title: Change the scale-policy of OpenGL ES in Android?
I currently develop a game for Android in OpenGL ES 1.0, use libgdx library. I target the 720x480 screen size.

For example, I design only one arts pack for 720x480. And what will happen in Android phones with screen-size smaller or bigger than it, 480x320 for instance? Could you please tell me how to change the scale-policy of OpenGL ES in Android? Or in libgdx specially?

Is there anything like "Resample Image" like photoshop?(Nearest Neighbor, Bilinear, Bicubic etc..) for libgdx?

**Edit**: I found some tutorials about texture filter in OpenGL, test it with Linear and Nearest. Linear is good for scaling but slow down the game, and Nearest is on the contrary. What should I do to get a balance between those?

# Answer
If you make the graphics for the average sized target device, the bigger screens will clearly notice the stretching, distortion, aliasing, etc. People will know the game wasn't made for their device unless its running pixel art, which in many cases still feels good in any resolution.

Then, when stretching down the assets, you usually get less issues and less quality loss as when increasing, so this should be the optimal way to go.

Since you want only one set of graphics (to avoid huge .APK files) here's my recommendation. Use texture atlases for everything you can, and fit as much as possible in the same atlas to save space. The graphics you pack into those atlases, make sure they look good in the bigger screensizes, even target 720p or 1080p if you so desire (remember tablets). With all graphics made for big screens and packed tightly as possible, find the format that best suits size with lossless compression. I usually use .PNG. Try with different image editors and find the one that will write the most optimized PNG file for optimal size.

In android, a good size for texture atlases is 2048x2048, according to my research. It can fit images that cover a full HD screen(1080p), its a power of two size, it can fit many ui elements and graphics together in the same texture (this also improves rendering performance a lot). If you don't need this much size, just use something below it. If you think about using textures bigger than this size, please don't. Many devices won't support it and you will waste people's time installing your application. Even 2048x2048 is not fully safe to use on older hardware, but many low-end android devices support it these days.

Now that you ensured the best quality/filesize ratio that covers all screens, there is the aspect ratio issues. Try to avoid black bars if possible, as many people don't like those, especially when their screen is already small and they are covering it a bit with the touches. Whats the most adequate is usually dynamic positioned UI that fits a given pattern in the screen, working for all resolutions more or less appropriately. As for the gameplay camera, what I usually do is to choose a fixed size for either width or height, then set the other dimension to something relative to ensure aspect ratio on all screens (prevents graphics stretching non-uniformly completely).

Having a game with a nice aspect ratio, placement of UI controls and assets oriented for all screens, if you still aren't satisfied with how the assets look stretched down to lower screens, you could activate smoothing on all textures, also known as texture filtering, syntax may vary in different API's and I never used libgdx. If you still aren't satisfied from the relatively poor results with the previous solution, then you should look into some image-based antialiasing approaches or perhaps some blur to hide detail and therefore hide stretching problems, if it applies to your asset style.

Hope it helps. Sorry for the lengthy answer.
> 1 votes

# Answer
The best policy for something like this is to make multiple assets. One for the larger screen size and another for the smaller screen size. Alternatively choose a middle ground and compromise slightly on performance.

Then when you first start your app, before loading any of the assets, check the dimensions of the screen using

```
Gdx.graphics.getWidth();
Gdx.graphics.getHeight();

```

and chose the correct assets to load respectively.

Another helpful hint is that if you want to maintain aspect ration on Android you can use

```
 AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
 cfg.resolutionStrategy = new RatioResolutionStrategy(16, 9);
 initialize(new MyGdxGame(), cfg);

```

in your Android Application. On say a 4:3 tablet (like my HP Touchpad) this puts black bars around my application, making it 16:9

Hope this helps
> 0 votes

---
Tags: android, libgdx
---


title: Idle/Moving FPS

text:
# Question
Title: Idle/Moving FPS
Lets assume I have an object that consists of 70,000 triangles. Would the FPS be more when the object is idle or when the object is moving? Thanks

# Answer
> 4 votes
As usual with performance questions, the answer is "it depends."

We certainly wouldn't expect a moving object to be cheaper than a stationary one, so in most cases it's a safe bet that idle FPS will be at least as good as moving FPS.

So, what might make moving FPS lower?

* Physics calculations. In most physics engines, objects that aren't moving are put to "sleep," so they incur little to no calculation load. Waking them up might drop framerate, even if the object isn't pushing on anything else in the scene. This may apply to other gameplay calculations too.
* Animation. If the movement is due to a skinned, morph, or procedural animation, the calculations driving that animation have some cost.

Those are the most likely culprits if you're seeing a substantial drop.

I would not generally expect a moving object to incur a significant additional cost for rendering, unless:

1. It's getting closer/moving out of occlusion (or revealing objects formerly occluded behind itself), meaning more pixels need to be shaded than before. This is a drop relative to the previous moment, but not a drop relative to the object remaining stationary in its new position/orientation.
2. The movement of the object forces a change in the scene data structures - say, resorting a bunch of translucent geometry so it renders in the right order, switching Level of Detail, forcing a shadow map switch/resize, or updating occlusion information.
3. Some effect in the scene does more work on moving objects - for instance, a trail renderer or motion blur that has to process more pixels when there's movement in the scene.

These should normally be small fluctuations - game rendering pipelines are built assuming objects will move a lot, so they're not too phased by most simple translations/rotations.

---
Tags: rendering, frame-rate
---


# Question
Title: Material properties and deferred renderering
I'm using assimp to import 3d models, and each model defines a set of material properties as well, such as material diffuseColor, ambientColor, specularColor and emissiveColor. Where would I store this information, in 4 additional textures, one for each material property or is there a smarter way?

Below is my current fragment shader for the first pass

```
"#version 330                                                                                \n \
                                                                                \n \
layout(std140) uniform;                                                                                \n \
                                                                                \n \
uniform UnifGeometry                                                                                \n \
{                                                                                \n \
    mat4 mWVPMatrix;                                                                                \n \
    mat4 mWorldMatrix;                                                                                \n \
    bool mHasDiffuseTexture;                                                                                \n \
    bool mHasNormalTexture;                                                                                \n \
    float mTextureTilingFactor;                                                                                \n \
} UnifGeometryPass;                                                                                \n \
                                                                                \n \
uniform sampler2D unifDiffuseTexture;                                                                                \n \
uniform sampler2D unifNormalTexture;                                                                                \n \
                                                                                \n \
in vec3 frag_position;                                                                                \n \
in vec3 frag_normal;                                                                                \n \
in vec2 frag_texcoord;                                                                                \n \
in vec3 frag_tangent;                                                                                \n \
in vec3 frag_bitangent;                                                                                \n \
                                                                                \n \
layout(location = 0) out vec3 outPosition;                                                                              \n \
layout(location = 1) out vec3 outNormal;                                                                                \n \
layout(location = 2) out vec3 outTexcoord;                                                                     \n \
layout(location = 3) out vec3 outColor;                                                                                \n \
                                                                                \n \
void main()                                                                                \n \
{                                                                                \n \
    outPosition = frag_position;                                                                                \n \
                                                                                \n \
    if (UnifGeometryPass.mHasNormalTexture)                                                                             \n \
    {                                                                                \n \
        vec3 normalTangentSpace  = normalize(texture(unifNormalTexture, frag_texcoord).xyz * 2.0 - 1.0);                \n \
        mat3 tangentToWorldSpace = mat3(normalize(frag_tangent), normalize(frag_bitangent), normalize(frag_normal));    \n \
                                                                                \n \
        outNormal = tangentToWorldSpace * normalTangentSpace;                                                           \n \
    }                                                                                \n \
    else                                                                                \n \
        outNormal = normalize(frag_normal);                                                                             \n \
                                                                                \n \
    outTexcoord = vec3(frag_texcoord, 0.0);                                                                             \n \
                                                                                \n \
    if (UnifGeometryPass.mHasDiffuseTexture)                                                                            \n \
        outColor = texture(unifDiffuseTexture, frag_texcoord).xyz;                                                      \n \
    else                                                                                \n \
        outColor = vec3(1.0);                                                                                \n \
}                                                                                \n";

```

# Answer
> 1 votes
* If the properties are uniform across the object (exact same value on every part of the surface), then you could sen them as additional uniform values per object or as instanced uniform.
* If there are slight variations (per-triangle variations), then sending values as attributes might be an option.
* If properties really differ on different parts of the object then textures might be the only way.

It really depends upon your needs, but it is either sending them like textures or as one per-instance uniform value.

---

As for how to store them:

You have four framebuffers, each with four channels. Plenty of room to store any information that you might need.

* 1st fb: RGB - position, A - specular
* 2nd fb: RGB - normal, A - ?
* 3rd fb: RGB - diffuse color, A - ?
* 4th fb: RGB - emissive, A - ?

So you basically have 3 more channels to store the information you need.

If you need more space, there's a way to pack `normals` and `position` in only two channels.

Hope this helps.

---
Tags: opengl, c++, deferred-rendering, deferred-shading
---


# Question
Title: How to continuously create objects in front of the camera when moving forward?
I have created a scene in Unity3D that's filled with spheres. I want to be able to move forward forever and still be passing through the spheres.

I was thinking I'd keep the player in one spot and move the spheres. Maybe destroy the previous bunch of spheres and create a new bunch in random coordinates? I really don't have idea how to start.

# Answer
Sounds like you are looking for something like a sliding window effect, centred around the camera position. I'm going to gloss over how you're spawning the spheres initially, because that will very much depend on how your scene is setup, but rather than destroying and creating spheres it may be more efficient to simply move them to where you want them to be. Here's some off-the-cuff C# code that should get you started. It assumes that you have a list of `spheres` which is pre-populated with a bunch of GameObjects that you're going to render. Also key is knowing where the camera moved from to where it is now (because you need that information to decide where you're going to spawn the new spheres.

```
Vector3 previousCameraPosition;
void Update()
{
    Vector3 cameraPosition = camera.transform.position;
    Vector3 movement = cameraPosition - previousCameraPosition;
    const float kInterestRadius = 1000.0f;

    List<GameObject> spheresToPrune = new List<GameObject>();
    foreach (GameObject sphere in spheres)
    {
        Vector3 spherePosition = sphere.transform.position;
        float distanceToCamera = Vector3.Distance(cameraPosition, spherePosition);
        bool isWithinCameraSphere = (distanceToCamera < kInterestRadius);

        if (!isWithinCameraSphere)
        {
            spheresToPrune.Add(sphere);
        }
    }

    //Take all the spheres that fell out of the back of the moving window,
    // and shift them to random positions near the front of the window.
    // Since we're sweeping a sphere, that means the front hemisphere.
    // Easiest way to pick a random point on a hemisphere is through polar
    // co-ordinates
    foreach (GameObject sphere in spheresToPrune)
    {
        // Azimuth of 0 and inclination of 0 == straight forward in the direction of camera motion
        // -90 degrees azimuth == left from camera motion
        // 90 degrees elevation == up from camera motion

        //Pick an azimuth in the front 180 degree sweep
        float azimuth = UnityEngine.Random.Range(-90.0f, 90.0f);
        //Pick random inclination
        float inclination = UnityEngine.Random.Range(-90.0f, 90.0f);

        // NB: you may have to juggle the parameter order
        // so that the rotation correctly transforms the position as you expect
        // in your own coordinate system
        Quaternion rotation = Quaternion.Euler(azimuth, inclination, 0.0f);

        // Alter the camera movement vector by the rotation so that it points towards the new position
        Vector3 rotatedMovement = (rotation * movement);

        // Push the direction out to the very edge of the sphere
        Vector3 newPosition = rotatedMovement * kInterestRadius;

        //Shift the sphere that was pruned to its new position
        //Alternately, destroy the pruned sphere (calling spheres.Remove to
        // delete it from the list of spheres), and then create a new one in the new position
        sphere.transform.localPosition = newPosition;
    }

}

```
> 2 votes

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


# Question
Title: Particles placed in the middle of the screen (OpenGL ES 2 / Android)
It seems like each of my particles is placed at `(0, 0, 0)` even though I'm setting different positions for each of them (debugger also confirms this). It must be something really silly that I'm missing. My intention is to paint 250 particles at random positions on the screen. Here's my code:

```
@Override
public void onDrawFrame(GL10 gl) {
    if(time++ == MAXTIME) {
        time = 0;
    }

    //my own helper methods
    GLUtils.sendBufferData(a_Position, 3, position);
    GLUtils.sendBufferData(a_Velocity, 3, velocity);
    GLUtils.sendBufferData(a_Offset, 1, offset);

    Matrix.setIdentityM(mModelMatrix, 0);
    Matrix.multiplyMM(mMVPMatrix, 0, camera.getViewMatrix(), 0, mModelMatrix, 0);
    Matrix.multiplyMM(mMVPMatrix, 0, camera.getProjectionMatrix(), 0, mMVPMatrix, 0);

    GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);

    GLES20.glUniform1f(u_Time, time);

    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture);
    GLES20.glUniform1i(u_Texture, 0);

    GLES20.glDrawArrays(GLES20.GL_POINTS, 0, particlesCount); //particlesCount = 250
}

@Override
protected void initData() {
    float[] positions = new float[3 * count];
    float[] velocities = new float[3 * count];
    float[] offsets = new float[count];

    int index = 0;

    for(int i = 0; i < count; i++) {
        offsets[i] = MathUtils.random() * 60 + 20;

        positions[index] = MathUtils.random() * 2 - 1;
        velocities[index] = -0.025f;
        index++;

        positions[index] = MathUtils.random() * 2 - 1;
        velocities[index] = -0.035f;
        index++;

        positions[index] = 0;
        velocities[index] = 0;
        index++;
    }
    //my own helper method
    texture = GLUtils.loadTexture(mContext, R.drawable.snowflake);

    position = ByteBuffer.allocateDirect(positions.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
    velocity = ByteBuffer.allocateDirect(velocities.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
    offset = ByteBuffer.allocateDirect(offsets.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();

    position.put(positions).position(0);
    velocity.put(velocities).position(0);
    offset.put(offsets).position(0);
}

private static final String vertexShader() {
    return "" +
            "uniform mat4 u_MVPMatrix;\n" +
            "uniform float u_Lifetime;\n" +
            "uniform float u_CurrentTime;\n" +
            "\n" +
            "attribute vec4 a_Position;\n" +
            "attribute vec3 a_Velocity;\n" +
            "attribute float a_Offset;\n" +
            "\n" +
            "void main() {\n" +
            "    gl_PointSize = 10.0;\n" +
            "    gl_Position = u_MVPMatrix * a_Position;\n" +
            "}";
}

private static final String fragmentShader() {
    return "precision mediump float;\n" +
            "\n" +
            "uniform sampler2D u_Texture;\n" +
            "\n" +
            "void main() {\n" +
            "    gl_FragColor = texture2D(u_Texture, gl_PointCoord);\n" +
            "}";
}

```

Note: I deliberately deleted some lines from the vertex shader since I don't think they are relevant in this case.

Edit: It may be that `gl_PointCoord` is always set to 0. I'm looking into this now.

# Answer
> 1 votes
you allocate and initialize positions and velocities but never fill in the allocated buffers:

```
position = ByteBuffer.allocateDirect(positions.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
velocity = ByteBuffer.allocateDirect(velocities.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
offset = ByteBuffer.allocateDirect(offsets.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();

position.put(positions);
velocity.put(velocities);
offset.put(offsets);

```

---
Tags: opengl-es2, particles
---


# Question
Title: Adapting motion controls to changes in the player's orientation
I am using **gyroscope data** (pitch, roll) to **move the player's space ship**.

It works perfectly as long as you play in a standard position (e.g. sitting down).

Once you start using it lying down (e.g. in the bed), the control does not work anymore as the pitch and roll values I used become too big.

Here is the code I use, written in Objective-C. Any idea on how to improve/fix this?

```
-(void) gyroUpdate:(ccTime) delta
{
    CMAttitude * attitude;
    CMDeviceMotion * motion = [GameController sharedGameController].motionManager.deviceMotion;
    attitude = motion.attitude;

    float pitch =  attitude.pitch;
    float roll =  attitude.roll;

    ShooterScene * shooterScene = (ShooterScene *) [self parent];
    ShipEntity *playerSprite = [shooterScene playerShip];

    const float roolSpeed = 1000.0f;
    const float pitchSpeed = 1000.0f;

    //Midpoint of pitch is 0.5f, here the Player ship is NOT supposed to move.
    //Moving "forward" is equal to values towards 0.0f-
    //Moving "backwards" is equal to values towards 1.0f+

    float pitchProgression = 0.5f - pitch;

     CGPoint newPosition = CGPointMake(playerSprite.position.x + roll * delta * roolSpeed, playerSprite.position.y   + delta * pitchSpeed * pitchProgression );

    [playerSprite setPosition:newPosition];
}

```

# Answer
I solved a similar problem once with the Wii remote \- but we didn't have the gyroscopes & magnetometers common in mobile devices today (the Wii Motion Plus was just coming out at the time), just accelerometer. Here's a modified version of the approach...

1. Keep track of a reference frame - say, a current "up" and "right" vector, or a quaternion. Initialize it to something like an identity matrix.
2. Estimate how still the device is being held - by checking whether total acceleration is close to 1G for instance, or that all gyroscope axes are reporting close to zero.
3. Use this estimate to gradually increase or (more sharply) decrease a "learning factor" - a coefficient that's zero when the player is moving and approaches 1 when they've been still for a period of time.
4. Blend your reference frame toward the current "up" and "right" vectors or quaternion reported by the device's sensors, at a slow rate proportionate to your learning factor. (So when the learning factor is small during movement, you remain locked in your old coordinate system)
5. When reading motion data, transform it into your reference frame, and do all your gameplay calculations in that frame.

So now if the player holds the device on its side, they'll steer sharply to one side for a few seconds, but then the control input will gradually neutralize as they keep the new position, and input will be relative to this new position from then on.

Note that depending on the device, you might not have the ability to discern all axes of movement. For instance, if your device lacks a magnetometer, you won't have an absolute measure of yaw. If the player lays down sideways, what was formerly an axis you could measure absolutely (pitch) becomes one you can't (yaw), and you may get some drift. Working with relative values may help, or you can fake one axis of sensor input to keep it from drifting too far.
> 3 votes

---
Tags: ios, movement, mobile, user-experience, controllers
---


# Question
Title: Behavior trees - Can sequences and selectors contain conditions?
I can't wrap my head around this. Is it legal for parent nodes to contain additional logic ?

# Answer
> 5 votes
It wouldn't really make sense. Behavior trees have their conditionals at the leaf nodes. Those conditionals determine if the traversal will continue to the other leaf nodes in that parent, or move back up to the other parent nodes.

You seem to be talking more about decision trees, where it's expected to have logic in the parent nodes.

You can learn more about the two here: Decision Tree vs Behavior Tree

Further, just because it's not the standard way it's done, if you have the situation where you want to create this new data structure that has conditionals in the parent nodes of a behavior tree, go ahead and do it. Game design is a pretty "open to interpretation" kind of thing, so just do what works for you.

---
Tags: ai, behavior, tree
---


# Question
Title: In a ES system, how one would implement/ deal with Modifiers?
Given the normal entity-component-system architecture, lets say we a component that give the entity Strength. Now on the game flow I want to give +4 strength do to the wielded weapon. What would be the best way to do this, considering that.

BaseValue =\> 10; Weapon =\> +4; Weaken Spell -2 (Temporary); CurrentFinalValue =\> 12

I could have many modifiers, positive or negative; I would like to know for a given entity attribute "Strength", what are the modifiers sum; I could add or remove modifiers and they should not remove from the base "Strength";

I could add as a component (StrengthModifierComponent) and apply the change to the StrengthComponent, then to be able to calculate the CurrentFinalValue, I would have to discover every component that affects "Strength" somehow and sum it with BaseValue. This might be easier if I have complete control of the system, but if I am building the system for general purpose this would have to be dynamic and there for complicated, making it possibly "slow".

I cannot put in the entity since the entity is usually just an identifier (int,Guid,SomeUniqueName).

I could make a ModifiableComponent which accept a list of Modifiers and would allow an easier interaction when making all the calculus. But wouldn't this break the ES architecture?

Thanks you.

# Answer
Add the modifiers to the component that holds the value being modified. This means for the strength attribute, you'd add a list of strength modifiers to the component that defines the strength attribute. The modifiers are just data after all.

Then your systems will have no trouble accessing the modifiers because they'll already in the same component.
> 4 votes

# Answer
What you need are a component that sends out the damage dealt and one that receives the damage done, and applies any modifications to the damage before updating health.

The general workflow for an RPG type system can be modelled like so:

**Damage-Doer**

* may have a "base damage", for example based on the wielded and used weapon
* multiplies base damage with stats using custom formulas as desired
* may have modifiers, such as "wears enchanted staff of quadruple damage"
* sends a "packet" of damage information to the receiving entity(s)

Damage information contains attributes like the base damage, the "type" of damage (ie fire, magic, piercing, etc) and other attributes as needed.

**Damage-Taker**

* analyzes damages for its type, may discard it entirely or just reduce it by a percentage (ie temporary protective force shield, immunity/resistances against magic, etc)
* modifies incoming damage according to custom formula, goes through modifiers (ie arrow considers armor and perhaps dexterity while magic damage may consider intelligence and wearing a funny hat)
* applies modified damage

Actual modifiers can be components too, but specific to the damage-doer and damage-taker components. I would give them different names (CombatModifiers), because there are other things besides resistances, shields, power-ups that can be relevant RPG modifiers during combat. Like an Ability to resist or be immune to certain spells (ie prevent boss monsters from being turned into a pet and subsequently not being able to kill it, unable to end the quest and reap the rewards).

So basically these are two components that send and receive information and process them accordingly. The above is only an example and depends on actual design requirements.

For example it may make sense to not calculate a total damage and leave it up to the damage-taker to generate the actual damage done. Based on the likelihood that the receiving end is going to modify the damage anyway, and may need to discard only certain components of the damage value such as discarding the +1 ice magic damage applied to the sword that just pierced through the armor and cut off a limb. Or vice versa. Also: random variation of damage, and critical hits, cause sometimes you're just lucky enough to hit the life-critical cheekbone arteria (I just made that up, but so is any damage in an RPG).
> 0 votes

---
Tags: c#, game-design, architecture, entity-system, .net
---


title: MonoGame - when/how to save data

text:
# Question
Title: MonoGame - when/how to save data
I am making a simple 2d game for WP in monogame/xna and am at a point where I want to save data. I have created a method to serialize the data (index, counter and percentage counter) to an isolated storage file in xml format. There is also a subsequent method to deserialize the file. My question is simply, what point is best to save the game, because at the moment I save when the a pause screen is loaded over the gameplay screen - However, this wont save the data if the player exits the app. I am certain I am saving in a silly place. Hence, I am wondering what the common practice is for saving? Any help/advice would be greatly appreciated.

Here is my save method:

```
    public void SaveData()
    {
        const string filename = "data.vision";
#if WINDOWS_PHONE
        IsolatedStorageFile dataFile = IsolatedStorageFile.GetUserStoreForApplication();
#else
        IsolatedStorageFile dataFile = IsolatedStorageFile.GetUserStoreForDomain();
#endif
        try
        {
            // Create an isolated storage stream and initialize it as null.
            IsolatedStorageFileStream isolatedFileStream = null;

            // Check the data file already exists.
            if (dataFile.FileExists(filename))
            {
                // Open the file using the established file stream.
                using (isolatedFileStream = dataFile.OpenFile(filename, FileMode.Open, FileAccess.ReadWrite))
                {
                    // Read the data from the file.
                    XmlSerializer serializer = new XmlSerializer(typeof(Data));
                    // Store the deserialized data object.
                    Data savedData = (Data)serializer.Deserialize(isolatedFileStream);

                    // Loop through the LevelData objects within savedData.
                    for (int i = 0; i < savedData.Levels.Count; i++)
                    {
                        // Get the LevelData object in question.
                        LevelData levelData = savedData.Levels[i];

                        // Check to see if the index of the levelData object corresponds to the active level index.
                        if (levelData.Index == mLevelIndex)
                        {
                            // Increment the stored attempts by the current attempt counter.
                            levelData.Attempts += mLevel.AttemptCounter;

                            // Check if the stored completion percentage is less that the current percentage.
                            if (levelData.PercentComplete < mLevel.PercentComplete)
                                levelData.PercentComplete = mLevel.PercentComplete;

                            //System.Diagnostics.Debug.WriteLine("new attempts  " + levelData.PercentComplete);
                        }
                        // Update the level data element within the saved date.
                        savedData.Levels[i] = levelData;
                    }
                    // Set the position to the begining of the file.
                    isolatedFileStream.Seek(0, SeekOrigin.Begin);
                    // Serialize the new data object.
                    serializer.Serialize(isolatedFileStream, savedData);
                    // Set the length of the file.
                    isolatedFileStream.SetLength(isolatedFileStream.Position);
                }
            }
    }

```

# Answer
Saving the data on the pause screen is a good point to do so. Additionally you'll want to save your state on application close and on application deactivate, and reload the state on open and activate. These events are exposed in the MonoGame XAML template, but I'm not positive they are exposed on the non-XAML template, but I will check and edit this when I'm on front of a keyboard. Proper handling of the back button on Windows Phone will lead to the optimal and prescriptive solution.
> 1 votes

---
Tags: xna, c#, monogame, savegame, screen-management
---


title: Instantiate prefab in editor script

text:
# Question
Title: Instantiate prefab in editor script
I'm working on a script to battle against nested prefabs. The script finds and replaces certain prefabs with a new version of that prefab. Now finding the prefabs is easy:

```
prefabList.AddRange(GameObject.FindObjectsOfType(typeof(GameObject)).Where(x => x.name == "PrefabName"));

```

But how can you instantiate a prefab in an editor script when the prefab is not in a resources folder? From what I read the `PrefabUtility.InstantiatePrefab` is used to do that, but I need a reference to the object which is instantiated.

# Answer
> 2 votes
You have a number of options. For example, you can load a prefab by name, use the selected object(s) in the editor, or assign a prefab to a property through an Editor Window.

AssetDatabase.LoadAssetAtPath
Selection
Showing a property in an editor window

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