# Question
Title: Multiplayer Game Data Serialization Problems
I want to create a simple game that can be played with one to two player. I plan on using TCP sockets, Farseer Physics, XNA, a BinaryFormater and a Memorystream.

as far as i know i can't do the physics on both clients, or you'll end up with everything out of sync. So my Idea was to do the physics on the host side then send the Farseer World data to the other client, however it is un-serializable and I also realized this was a lot of data to send every tick.

I could just send the players movements back to the server and send a Texture2D to the client to be drawn, however a Texture2D is un-serializable as well. it has dawned on me i must be doing this completely wrong.

But this is how i am attempting to send the data:

```
[Serializable()]
class ServerData
{
    public Texture2D Test;

    public Vector2 Test2;
}

    static void SendData()
    {
        byte[] DataBuffer = null;

        MemoryStream stream = new MemoryStream();
        BinaryFormatter formatter = new BinaryFormatter();
        NetworkStream netStream = PlayerOneSocket.GetStream();

        ServerData ServerDataToSend = new ServerData();

        formatter.Serialize(stream, ServerDataToSend);
        DataBuffer = stream.ToArray();
        netStream.Write(DataBuffer, 0, DataBuffer.Length);
        netStream.Flush();
    }

```

what am i doing wrong or how do i do it right.

I've done basic server stuff before with custom classes and serialization, I'm just at a loss on how to make a multiplayer game.

Thanks for the help

# Answer
> 3 votes
Send logical data, not presentation. Most games will never send graphics or textures to other systems during gameplay. Each system should already have all the resources it needs to render the events; you just send information about which events have taken place.

---
Tags: xna, c#, farseer-physics-engine, socket, serialization
---


# Question
Title: What kind of graphics would you like better? [ pictures ]
I am looking forward to make an android game, something angrybirds style. I've already made my own engine and now have to decide what kind of graphics should I make.

It could be either realistic, like that

or a doodle-style like this

Right now the first one looks more appealing to me... on the other hand, doodle-graphics are very easy to draw and their transparency doesn't seem to slow down the engine much.

What do you think?

# Answer
There is really no depth perception in the doodle graphics approach which is why realistic version is likely to look more appealing. You can still use scribble-style graphics and still use some kind of visual "depth". Start by removing the "piece of paper"-background - there's room for more layers than one.
> 2 votes

---
Tags: android, game-design, graphics
---


# Question
Title: What is the proper way to maintain the angle of a gun mounted on a car?
So I am making a simple game. I want to put a gun on top of a car. I want to be able to control the angle of the gun. Basically it can go forward all the way so that it is parallel to the ground facing the direction the car is moving or it can point behind the car and any of the angles in between these positions.

I have something like the following right now but its not really working. Is there an better way to do this that I am not seeing?

```
#This will place the car
glPushMatrix()
glTranslatef(self.position.x,1.5,self.position.z)
glRotated(self.rotation, 0.0, 1.0, 0.0)
glScaled(0.5, 0.5, 0.5)
glCallList(self.model.gl_list)
glPopMatrix()

#This will place the gun on top
glPushMatrix()
glTranslatef(self.position.x,2.5,self.position.z)
glRotated(self.tube_angle, self.direction.z, 0.0, self.direction.x)
print self.direction.z
glRotated(45, self.position.z, 0.0, self.position.x)
glScaled(1.0, 0.5, 1.0)
glCallList(self.tube.gl_list)
glPopMatrix()

```

This almost works. It moves the gun up and down. But when the car moves around, the angle of the gun changes. Not what I want.

# Answer
> 1 votes
Make sure your glCallist does not include any kind of transforms, then

```
#This will place the car
glPushMatrix()
glTranslatef(self.position.x,1.5,self.position.z)
glRotated(self.rotation, 0.0, 1.0, 0.0)
glScaled(0.5, 0.5, 0.5)
glCallList(self.model.gl_list)

    #This will place the gun on top
    glPushMatrix()
    glTranslatef(0, 1, 0)
    glRotated(updownangle, 1, 0, 0)
    glRotated(leftrightangle, 0, 1, 0)
    glScaled(1.0, 0.5, 1.0)
    glCallList(self.tube.gl_list)
    glPopMatrix()

glPopMatrix()

```

---
Tags: opengl, 3d, pygame
---


# Question
Title: How do I produce "enjoyably" random, as opposed to pseudo-random?
I'm making a game which presents a number of different kinds of puzzles in sequence. I choose each puzzle with a pseudorandom number. For each puzzle, there are a number of variations. I choose the variation with another pseudorandom number. And so on.

The thing is, while this produces near-true randomness, this isn't what the player really wants. The player typically wants what they perceive to be and identify as random, but only if it doesn't tend to repeat puzzles. So, not really random. Just unpredictable.

Giving it some thought, I can imagine hacky ways of doing it. For example, temporarily eliminating the most recent N choices from the set of possibilities when selecting a new choice. Or assigning every choice an equal probability, reducing a choice's probability to zero on selection, and then increasing all probabilities slowly with each selection.

I assume there's an established way of doing this, but I just don't know the terminology so I can't find it. Anyone know? Or has anyone solved this in a pleasing way?

# Answer
If you have a finite number of puzzles, you can:

* Build a list of puzzles, either all of them or some randomly picked;
* Shuffle this list (see the Knuth Shuffle for instance);
* Let your player play through this list;
* When the list is empty, start with a new one.

**EDIT**

I didn't know this, but browsing SE made me realize that this is actually known as a "shuffle bag". Some more infos here, here or there.

**EDIT 2**

The classic Knuth Shuffle goes this way:

```
To shuffle an array a of n elements (indices 0..n-1):
    for i from n − 1 down to 1 do
        j ← random integer with 0 ≤ j ≤ i
        exchange a[j] and a[i]

```

Steven Stadnicki rightfully pointed out in his comment that this kind of thing doesn't prevent repetition on a reshuffle. A way to take this into account is to add a special case for the last item:

```
To reshuffle an array a of n elements and prevent repetitions (indices 0..n-1):
    return if n <= 2

    // Classic Knuth Shuffle for all items *except* the last one
    for i from n − 2 down to 1 do
        j ← random integer with 0 ≤ j ≤ i
        exchange a[j] and a[i]

    // Special case for the last item
    // Exchange it with an item which is *not* the first one
    r ← random integer with 1 ≤ r ≤ n - 1
    exchange a[r] and a[n - 1]

```
> 26 votes

# Answer
A variant on lorancou's approach: for each puzzle type, keep an array of (shuffled) puzzle numbers; then every time you hit a puzzle of that type, get the next number off the list. for instance, let's say you have Sudoku, Picross and Kenken puzzles, each with puzzles #1..6. You'd create three shuffled arrays of the numbers 1..6, one for each puzzle type:

* Sudoku: \[5, 6, 1, 3, 4, 2\]
* Picross: \[6, 2, 4, 1, 3, 5\]
* KenKen: \[3, 2, 5, 6, 4, 1\]

Now, you'd shuffle the puzzle types just like lorancu suggests; let's say it comes up \[Picross, Sudoku, Kenken\]. Then every time you hit a puzzle of a given type, use the next number in its 'shuffle list'; overall your puzzle presentation would be \[Sudoku #5, Picross #6, Kenken #3, Sudoku #6, Picross #2, Kenken #2, ...\]

If you don't want to keep the puzzles in the same overall order each time through the loop, then I think your 'choose randomly, ignoring the last few picks' option is the best. There are ways you can make this a little bit more efficient, too; for instance, let's say that you have 20 things and you want to ignore the last 5 picked. Then instead of randomly choosing a number 1..20 and 'rerolling' until you get one outside the last 5, instead just choose a number 1..15 and walk through your puzzle types that many steps, just skipping over any puzzle type that's been picked (you can do this easily by keeping a bit array that holds the last 5 picked puzzles).
> 2 votes

---
Tags: algorithm, random
---


title: Loading enemies in a 2d platformer

text:
# Question
Title: Loading enemies in a 2d platformer
What would be the best way to load enemies in a level. For example take Mario, are enemies rendered at their x,y positions as the game is loaded or when the player walks past a specific x value. Wouldn't this mean that you would have multiple if conditions checking whether the player has reached a specific x value to spawn an enemy; this doesn't seem like a very good solution to this problem at least to me.

What would be the recommended way?

# Answer
> 7 votes
The originals absolutely loaded the enemies as you got close to them, as loading all enemies at once was likely beyond the memory constraints of the older gaming hardware. A lot of crazy and now unnecessary tricks were used back then to minimize memory usage.

Today, I would still opt to loading them on demand as you neared their spawn locations, as it gives more flexibility. Also, you'll notice that in games like Mario, the enemies always appear in the same place moving the same way; so even if you loade them in advance, you'd have to disable their movement until Mario got close enough.

There should be no question about the number of "if" statements, as you should absolutely not be writing code to spawn specific enemies on a specific map. Write a data file to describe your level and enemy spawn points, and then write a single generic block of code to check to see if Mario has gotten close to any unspawned enemies from the data list.

As much as possible, make everything data driven. Hard coded logic makes development slower and harder and, as you pointed out, just isn't a good solution to this problem.

---
Tags: game-design, level-design
---


# Question
Title: Is continuous loop best idea for Android OpenGL game?
I've done some small OpenGL games for computer. I've used continuous loop (with VSync) for game life cycle, input - update - render. Now i'm going to write simple game for Android, but i'm wondering if it is the right way to go.

What matters? Battery usage, i've played some simple games that used so much battery compared to their complexity and graphics and i don't wanna to create that battery hungry game.

# Answer
> 5 votes
You technically will always want a continuous loop. What you may consider is making that loop wait for user input events before redrawing the screen or processing game logic.

If the game is not real time and doesnt need animations to always be playing, it's absolutely a good idea to be event driven.

(Update for clarity): Note that by event driven I mean that the loop should call to the platform's "block and wait until an input message occurs" API. Not sure what that is on Android. On many platforms, it means calling a "Get" function rather than a "Poll" function.

---
Tags: opengl, android
---


# Question
Title: Frustum Culling/Only rendering what's viewed by the Camera in HTML5 Canvas?
I coded up a simple 2D Camera for my HTML5 Canvas-Based Game Engine but I noticed the performance wasn't very good. So a lot of people suggested only rendering things that are shown by the camera but I haven't found anything that helps how to implement this.

I'm thinking about iterating over through all my game entities then checking their rendering positions, etc. But is this efficient?

```
if(renderCoords[i].x >= 0 &&
   renderCoords[i].y >= 0 &&
   renderCoords[i].x <= camera.getWidth()+camera.offset.x &&
   renderCoords[i].y <= camera.getHeight()+camera.offset.y) {
       //render
}

```

It's not tiled-based, just thought I mentioned that. Just doesn't seem clean to me.

# Answer
> 3 votes
For a small 2D game, there nothing inherently wrong with this approach. Rendering is indeed costly, but looping over objects shouldn't be an issue (except if you really have tons of them, then look for a good space partitioning scheme). So keeping your rendering loop and discarding objects with such a test should be fine.

I'm not sure about your conditions though, especially what that camera offset is supposed to be (is that a camera position?)... But your general idea is OK.

And the classical advice: profile before you optimize, re-profile when done, and make sure your changes give you a significant improvement.

# Answer
> 0 votes
It's not clear to me that your code above is correct, should the bounds not be camera.offset.x and camera.getWidth() + camera.offset.x (and similar for Y)?

It might make more sense in the code, to assign local variables to the viewport leftx, topy, rightx, bottomy and then test if the objects bounding-boxes are in that range.

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


# Question
Title: Word for the combination of location and orientation (other than transform)
I'm trying to come up with a name for a class that encompasses an entity's position and orientation. This class isn't a transformation in the 3D sense- a transformation is something this class might create in order to tell the 3D where to draw. This class is meant to describe where an entity is.

I just know there's a good word for this!

# Answer
How about PositionState? Could also include other state parameters of the position like bounding box issues.
> 1 votes

# Answer
Some ideas from a thesaurus: abode, locus, place, placing, placement, position, post, seat, setting, site, spot, station
> 1 votes

# Answer
How about 'CurrentState'? or 'CurrentTransformationalState'? Or just 'TransformState'?
> 1 votes

---
Tags: terminology
---


title: 'Real' AI that learns in games

text:
# Question
Title: 'Real' AI that learns in games
In my work I analyze and design Evolutionary Algorithms (EAs), but for fun I'm learning game design, and, of course application of EAs in games. So I'm wondering if there have been any games where AI actually works as AI, i.e. learns from past solutions to develop new ones. I suspect it should be something like tic-tac-toe or chess.

# Answer
> 3 votes
Since you mentioned genetic algorithms and not specifically unsupervised learning, I thought you may find this interesting: http://boxcar2d.com/

It uses genetic algorithms to mutate better cars for the terrain based on each generations fitness. This is one of the most direct uses of EAs that I've seen that seem to be what you're looking for.

If you're looking for unsupervised learning as opposed to EAs, I can't help much since my experience is in the latter. Hope this was helpful.

I'de note this could also be done for tic tac toe or chess as you mentioned, the difficulty is just in modeling the genomes correctly to come to a solution (not necessarily a correct one).

# Answer
> 3 votes
While I cannot think of any commercially available games which did this, you may be interested in some of the AI challenges that resulted in such AI, perhaps most notably StarCraft's Berkeley Overmind. http://overmind.cs.berkeley.edu/

# Answer
> 0 votes
I would imagine that it's just too easy to fudge the AI and make them act intelligent instead of work intelligently. Most commercial game engines come with some basic AI capacity that eliminates most of the incentive to really build something new and cool anyway.

For the cases you mentioned, tic-tac-toe has been completely solved for quite a while now (http://xkcd.com/832/) and while chess has not (way too many permutations to really be viable) the basic algorithms, ie those that would be useful in the real time setting of a game, aren't really learning algorithms, they simply rank available moves.

# Answer
> 0 votes
I can't cite specific examples, but the guest on this show http://www.se-radio.net/2008/04/episode-92-introduction-to-game-development/ says that's a common practice to use Genetic Programming (or other heuristics) to make an AI

The advantage of using this natural computing approaches to AI is that you can create artifical dumbness without too much trouble, wich is generally desirable. Because as we know, for some games a perfect AI is trivial to do, but a 'human-like' one is not.

---
Tags: software-engineering, ai
---


# Question
Title: If I make a 3d model in a .fbx format, do I owe any royalties/fees to autodesk for using fbx files in Unity?
I'm currently making a game where every format for every asset is either opensource/freeformat, or requires no license fees to use.

I've pretty much settled happily on .ogg for audio, vorbis/webm for video, .png for pictures and openoffice for documents (or .pdf files since they were free standard since 2001?)

What I'd like to know though is, if I make a 3d model in a .fbx format, do I owe any royalties/fees to autodesk for using fbx files in Unity?

If not, does this apply to every 3d model format, or only certain ones? Do software companies like Blender/Unity pay for the privilege to import fbx files so that users like me don't have to?

# Answer
> 2 votes
For using the fbx file format. No.

However, most of the free versions of software are intended for student use only and are not for commercial use.

Check the software's licensing to be sure.

---

I am not a lawyer.

If you're using Blender you're safe.

---
Tags: unity, legal, fbx, import
---


# Question
Title: Handle many lights in a scene (with shaders)
I'm curious about how to handle many lights in a scene. Given a very big map in a role playing game, with dungeons (with lights in there) etc. I know about deferred lighting, but that only answers how to render many lights. But my question is more: How to *not* render many lights. It's obviously desirable to only render the lights effecting the scene, but I don't know a technique/an algorithm to archive this. Nobody wants or is even able to render 500 point lights, just because there somewhere in the map. But one cannot just take a straight line from the light to the player and test if something is in between. The distance also doesn't seem like a good indicator. (Sunlight?)

tl;dr: How can I figure out which lights affect the scene to only render them?

# Answer
> 5 votes
Even simpler than bounding volumes;

Assign a radius to each light. When it comes to rendering your scene, simply check to see if the distance between your scene objects and each light is less than the light's radius. If so, use the light, else, skip it.

Just a fraction more complicated, depending on how important performance is:

You can do a sort of broad phase check with this too. Just define a spacial grid that stores handles to your lights on a grid cell basis, then only perform the distance check on lights that are in the cells within the max radius of your scene objects.

# Answer
> 5 votes
The simplest way I can think of (lets be honest, the only way I've thought of) is to give each light a bounding volume. If the bounding volume intersects with the view frustum (or a bounding volume of the view frustum), apply the light.

There could still be lights that are applied even though they do not affect any visible objects but it is simple and fast. Smart arrangement of your scene graph could mean that just a few intersection checks cull most of your lights (just like what is done for object culling).

Something like the sun could have no bounding volume (to denote it should always be applied).

---
Tags: opengl, directx, shaders, lighting
---


# Question
Title: Problem rendering a Wavefront mesh, nothing displays(VBO)
I'm having a problem with displaying my wavefront obj file using VBO's My fps counter slows down like there is something being drawn but I cannot see anything. Is it a problem with my loader? Or maybe just a simple bug in my VBO rendering code?

I have checked that I am actually loading the data but maybe it's in the wrong order. I used OpenGL profiler and found nothing specious the texture and the VBO and IBO are in the GPU. I did try two different obj files, one of mine and a random one I found on NASA's site both rendered at the same speed(about 60 fps) with nothing on the screen. If you want any output from OpenGL profiler ask me.

BlockRender.cpp http://pastebin.com/3KuuWX9H

Renderer.cpp http://pastebin.com/gDCvi3t7

Relevant snippets of code http://pastebin.com/rTqRzYXL

Sample wavefront obj file http://pastebin.com/qVJ55gwn

# Answer
Some observations:

* *First, there's no error checking in the code.*
* The obj loading seems incorrect.

The vertices are copied into `mesh.vertices` (l. 212-214 in BlockRenderer). Using the DefaultCube, `mesh.vertices` contains 12\*3 vertices, and the index buffer 36 ints.

Problem seems that the indices reference into the original `verts` array and not into `mesh.vertices`. BlockRenderer.cpp l.216ff should IMO read like

```
mesh.indices.push_back(3*i+0); // not faces[i].v[0]
mesh.indices.push_back(3*i+1); // not faces[i].v[1]
mesh.indices.push_back(3*i+2); // not faces[i].v[2]

```
* However, when using indices, I'd expect the original vertices to stay untouched, and the faces defined by the indices. Then, the vertex buffer must contain 24 floats defining 8 vertices that define the cube's corners. For building the vertex buffer, the code needs to iterate over `verts` and just push the vertices into `mesh.vertices`; the corresponding index buffer then is built using the original code.
* You're sure the mesh is a triangle strip?
* Why not using an asset loading library?
> 2 votes

---
Tags: c++, opengl, 3d-meshes, vbo, obj
---


# Question
Title: Side detection on Rectangle collision detection?
How can I determine which of the sides on a Rectangle that was hit by another Rectangle (or Circle if that's easier)?

I originally tried creating 8 subrectangles for my main rectangle - one for each side and corner - with the appropriate length and width of one pixel. This didn't work out very well though, to my understanding it was thwarted by the speed and update frequency...

Any thoughts?

# Answer
> 2 votes
I found this to be quite a thorny problem recently. I have a fully working Box-Sphere system up and running now though.

My solution was to represent my rectangle as 4 planes. I test the sphere centre's distance from each plane and compare this to the sphere radius to see if there is an intersection (you do this with the framework Plane.DotCoordinate method). At the same time I count how many distances are positive - this is effectively a check to see if the point is in front of each plane. Finally I accumulate the the normals & distances of the intersecting planes to make a single composite 'collision vector' to deal with edge and corner collisions with multiple planes.

Once you have these 3 bits of info you can check a few things:

1. If you are in front of *none* of the planes, definitely a collision and just check to see which one is intersecting to find which side was hit.

a. In front of *no* planes, but no intersections - complete containment. This is the worst case and I cast back a ray along the objects velocity vector to see which side it hit on its way in.

2. In front of the same number of planes as there are intersections. This maybe a collision, but only if the intersection distance along the collision vector is less than the sphere radius. This case actually deals with face, edge and corner collisions (1, 2 or 3+ planes) in one go.

I hope you can follow such a long-description, but the logic is probably more important than the code.

Plus, a major upside of this this approach is it is trivially generalisable to 3D and you can add as many planes as you like to define the collision volume - provided your shape always remains convex. This technique is a version of the pattern often called Discrete Orientated Polytopes - or DOP if you want to look it up in the literature I think.

I did an online presentation for Microsoft UK Tech Days. If you want to see the slides detailing the process above, check here.

# Answer
> 1 votes
Compare the X and Y coordinates of both rectangles. Apart from strange cases (like one rectangle being submerged entirely in another, or one rectangle being a super-set of the other) these should be sufficient to tell you.

If you have the middle-point of the two shapes, that might also be an easier way to tell the relative positioning of the two objects.

# Answer
> 0 votes
Gosh I find myself referring to my code a lot =D

What I do is check your previous position, to see if it was previously outside of the rectangle, this works flawlessly in my game engine =)

to get the previous position I use an update method, which I call once a frame.

# Answer
> 0 votes
```
            if (DestinationRectangle.Intersects(collisionRect))
            {
                touchingTheLeftSide = (previousPosition.X + previousPosition.Width) <= collisionRect.X;

                touchingTheRightSide = previousPosition.X >= (collisionRect.X + collisionRect.Width);

                sittingOnTop = (previousPosition.Y + previousPosition.Height) <= collisionRect.Y;
            }

            previousPosition = DestinationRectangle;

```

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


# Question
Title: How can a NodeJS server be used from Game Maker HTML5?
I want to create a client-server game that runs on Game Maker HTML5-NodeJS. The NodeJS server will be an AI server - a bot that acts like a human opponent and plays against the human player at a front-end game client that is coded in GM HTML5.

How can a NodeJS server be used from GM HTML5. Are there any examples of such a system?

I already got an iOS game that can talk to a remote AI server (coded in Lua) using TCP sockets. Can this be done with Game Maker HTML5 and NodeJS.

# Answer
> 1 votes
Game Maker HTML5 is supposed to have an "Internal code editor with user definable syntax colouring". So if you're able to write some Javascript on the client side, you can use socket.io. It's a node.js module that does WebSockets and way more, and it's really easy to use.

# Answer
> 1 votes
If you can modify the generated HTML5, then yes, of course it can.

For communication, use socket.io, it's a great library that I've used to make a simple MMO (dev blog: http://yannbane.blogspot.com/).

You can find great examples on their site: http://socket.io/.

To install socket.io, you must do:

`npm install socket.io`

To use it on server-side:

`var io = require('socket.io');`

And on client-side:

`<script src="/socket.io/socket.io.js"></script>`

---
Tags: html5, client-server, node.js, game-maker
---


# Question
Title: a simple 2D rectangle collision algorithm that also determines which sides that the rectangles collide?
I initially tried out implementing rectangular intersection, which works well. However, when I have to apply the physics system, such as velocity, acceleration, and directional vectors, I would have to find a way to determine which side of the rectangles collide. Now, in my system, there is no rotated rectangle, so this simplified the problem. However, I couldn't find an easy way to determine which rectangle side collided. I have once deal with this problem before but failed miserably.

What I did in the past is determine the distance between each parallel rectangular sides and check if the distance is close to 0 (use some initially defined distance range) or is 0. However, for floating-point arithmetic, this proves to be unstable because of unknown time elapse. Sometime, the rectangles would actually intersect each other before it meets the defined range.

On the other hand, I was thinking about spawning multiple rectangles, each rectangle for each sides. However, after thinking again, it would be the same thing as having a parallel side with distance range checking, just that that distance range is the width of each mini-rectangle.

Therefore, any suggestion to this problem?

# Answer
Adapted from my answer to "Which Side Was Hit?":

I suggest computing the Minkowski sum of B and A, which is a new rectangle, and checking where the centre of rectangle A lies relatively to that new rectangle (to know *whether* a collision is happening) and to its diagonals (to know *where* the collision is happening):

```
float w = 0.5 * (A.width() + B.width());
float h = 0.5 * (A.height() + B.height());
float dx = A.centerX() - B.centerX();
float dy = A.centerY() - B.centerY();

if (abs(dx) <= w && abs(dy) <= h)
{
    /* collision! */
    float wy = w * dy;
    float hx = h * dx;

    if (wy > hx)
        if (wy > -hx)
            /* collision at the top */
        else
            /* on the left */
    else
        if (wy > -hx)
            /* on the right */
        else
            /* at the bottom */
}

```
> 24 votes

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


title: Separating game logic from animation

text:
# Question
Title: Separating game logic from animation
For non-game applications the model-view-controller pattern is typical where data, logic, and visuals are separated. But for a game how would you architect the game logic and the animation system in this way?

The gut instinct is to just not think about this and jam the 3d model and its animations into the Unit class where there is also the unit attack logic. And then to just to intermix the code that runs the attack logic with the attack animation. But suppose you wanted to keep these animations separated. What kind of design pattern would you use?

Perhaps a way of testing a design to see if its good is to see if it allows reasonably easy replacement. Imagine replacing the the 3d polygonal animation system with a voxel animation system. What kind of design pattern and game architecture would make this easy? Obviously just intermixing the code that runs the attack logic with the attack animation would make this hard.

# Answer
You should strive for data-driven animations.

I especially advise that you do a bit of research around *Blend Trees*, they're the most powerful and flexible design I've seen so far. Read this for a few references.
> 4 votes

# Answer
Well you wouldn't really do an mvc design directly in a game as games generally have a specific set of requirements, content, and functionality. In terms of keeping thing separate, you could have class based animations for example, like all humans walk so that can be a bone animation. Then from there, each model/unit would have various actions that are tied to a specific animation group. But just remember, things in games are often scripted and most games choose speed over flexibility. See how something like UDK does it
> 0 votes

# Answer
I wouldn't necessarily use an MVC design for individual units (at my company we do take that approach with the UI) but rather a component architecture. You can look up "component design" in other questions, but the gist is that Unit is comprised of a collection of loosely coupled components, of which AIComponent and AnimatedModelComponent are just two.
> 0 votes

# Answer
A strict MVC approach is generally geared towards GUI applications so it's not always very applicable to games. However there is still much benefit in separating logic from presentation where possible. At the very least the renderable part and the animations should be stored as a subobject of the unit in your game, so that the rest of the unit code isn't mixed in with the graphics. Perhaps a better approach is to have the renderable object hold a reference to the unit so that the animation system can examine the unit's current state and properties to produce the correct visuals. You may find an Observer pattern useful here, so that changes to the unit can be immediately picked up by the rendering side, without the unit needing to know anything about rendering specifics.
> 0 votes

---
Tags: architecture, software-engineering, animation, design-patterns
---


title: Sound Delay With AVAudio Player

text:
# Question
Title: Sound Delay With AVAudio Player
I'm using the following code in my viewDidLoad to load a sound:

```
NSURL * url = [NSURL fileURLWithPath:
   [NSString stringWithFormat:@"%@/Moto - Hit Sound.mp3",
   [[NSBundle mainBundle] resourcePath]]];
NSError * error;
hitSoundPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
hitSoundPlayer.numberOfLoops = 0;

```

Then I'm using this in a void method to play the sound:

```
if(CGRectIntersectsRect(main.frame, enemy1.frame)){
    [hitSoundPlayer play];
}

```

This does seem to work, however the first time the sound is played there is a lot of lag and the game stops temporarily. I'm using this same method for when in an `IBAction` and it works fine, it must be the fact that it's also detecting a collision that makes the sound lag. If I want to be able to play sounds quickly and on the spot without any sort of lag am I doing the right thing? Do I want to use another method? I'm not using any frameworks like cocos2d. If you need to see any more code just ask.

# Answer
Try calling prepareToPlay after AVAudioPlayer is initialised.

```
[hitSoundPlayer prepareToPlay];

```

Also, if AVAudioPlayer is not the first initialised it might not be using the hardware to play the audio?
> 1 votes

---
Tags: iphone, sound
---


# Question
Title: Dynamically Deformable Terrain In Game Engine
I am looking for a game engine that is open to the public for free or at a payed price that allows for any reasonable way of doing deformable terrain over a network. The closest I have found to this is in udk where one can build a terrain in 3ds, cut it up, and import different chunks into udk, and fracture them. Unfortunately after a few hours work I discovered that this doesn't seem to work too well for what I am trying to do. Can anyone recommend a game engine, or even a rendering engine that supports this? Programming other features into a rendering engine is not an issue for me.

# Answer
> 0 votes
OGRE has something like that.

Overhang Terrain Scene Manager

---
Tags: rendering, networking, terrain
---


title: Cocos2d particle system

text:
# Question
Title: Cocos2d particle system
I have a fire particle emitter in my project and I have it following a football. My goal is to make the football look like it is on fire but the problem is when I add it to the screen it can only be in front of the football or behind it. I want to be able to add it to the screen and make it transparent so that the football will still show through to a certain point. Does anyone now how I would go about doing this?

# Answer
> 2 votes
I would go with this method:

1. draw the ball object,
2. then draw the particles over it with alpha blending enabled
3. redraw the ball in exact same position but this time use lower opacity for the whole sprite (maybe something around 40%)

This way you'll both see the ball everywhere even if no particles are drawn at that pixel(caused by the back ball picture), and you can always see the ball.

And for blending method just use the normal function implemented by default.

---
Tags: cocos2d-iphone, cocos2d
---


# Question
Title: Multiple, independent animations for one character
I'm using XNA, and I'm well versed with the skinnedModel sample. I'm starting to make my own models and animations. I'd like to be able to take animations that apply to different, independent body parts and combine them. For example:

Let's say I have some animations for my characters body:

* running
* walking
* standing

I also have some animations for my characters face:

* frowning
* smiling

Ideally, I'd like my character to have any facial expression when doing any action. So, they could be:

* walking while smiling.
* walking while frowning.
* running while smiling.
* running while frowning
* ... and so on ...

However, I'm not sure how I should best manage this. I know that I could make N\*M different animations (where N is the number of body animations and M is the number of face animations) and import them all, but this seems like a lot of work as the number of animations starts to increase.

If anyone has a smart way to handle this, I'd love to hear it.

# Answer
> 1 votes
The technique you're looking for is called "animation blending."

At the simplest level, this means that you take the bone positions of all current animations and "average" them out.

The skinned mesh sample should be easy to modify to do this yourself.

There is a lot more math behind doing things "right" but that'll get you started and you should be able to google more information now that you have the right keywords to search on.

# Answer
> 0 votes
Well, if you want something X and Y which can be combined freely, then you composition. For that you need to make parts X and Y independent from each other. Thus, as @GustavoMaciel suggests you need to separate face and body parts.

However the challenge here lies in the ability to combine parts smothly. So it can be quite possible that drawing all possible combinations can produce better results.

---
Tags: xna, animation
---


# Question
Title: Pathfinding using nodes/waypoints without connecting them?
I've been doing some research on pathfinding lately because I want to code a game modification for a game (won't say which exactly) and what I've done is defined a huge list of 3D vectors where a player can possibly go to. The thing is, I want to implement some sort of pathfinding system which can navigate from one of the points in the list to the other.

I've read some tutorials and websites about pathfinding like A\* and Dijkstra's algorithm but all those examples seems to use tiles/squares and are all in 2D environments...

So far, I'm performing some simple distance checks (for example, checking for any points that are less than 100 units away from the current one) and sight/bullet checks (to see if the point is walkable/accessible) and selecting the best point according to distance from the destination. This seems to work most of the time, however there are times where it may try to navigate along a dead end and just fail or it might do some strange, unneeded zig-zags as well as taking really long routes.

Have you guys got any ideas of any algorithms I could implement as well as provide some psuedo-code? That would be so great. I want to avoid having to define vertexes/edges or connecting these points because I find that the maps are so large/vast, it'd be too much trouble. I would only do that if it were a last resort.

# Answer
> 2 votes
A\* works on most any node graph, not just tiles. So long as you can compute a heuristic for the cost to travel between two nodes (distance in most simple cases works fine), you can use A\*.

The problem with finding the closest node to the selected point can be solved by doing a simple ray test (assuming relatively flat terrain). If the user picks a point, find the closest nodes that are "visible" from the selected point.

You can use that same approach (in an O(n^2) algorithm) to automatically generate connections between nodes you've placed.

It will be up to you to make sure that the nodes are placed close enough to each other and in all "crevices" in the map to ensure that the ray tests work (proximity may be particularly important of you have very "hilly" terrain).

You're going to want the ray tests anyway during patting to smooth out the paths.

---
Tags: algorithm, game-mechanics, path-finding, modding
---


# Question
Title: What Program Was Used To Make Call Of Duty?
i was wondering what program i should download to make my OWN version of COD I already know unity http://unity3d.com/ but no others. Could someone help me?

# Answer
Call of Duty was most likely programmed in C++ and DirectX.

Unity should be enough to "make your own version".
> 3 votes

---
Tags: game-design
---


title: One-way platforms in UDK

text:
# Question
Title: One-way platforms in UDK
I'm looking to make a multi-player platforming game using UDK. I'm currently doing feasibility research, to make sure I will reasonably be able to do all of the technical things I want to do. The first major hurdle I've come across without being able to find as answer, are one-way platforms.

That is to say, platforms through which a player can jump up, but not fall through (unless they choose to). These are commonly seen in games like Mario, Kirby and Smash Bros.

Does anyone know how such a system would work within UDK? I can think of solutions that might work for single-player, but not multi.

# Answer
From what I remember from UnrealScript before 3.x this would be possible but would require a custom player controller/player pawn and/or possibly a a custom Volume.

Basically when the player initiates commandDrop, a trace can be performed to see if the player is on the custom moving entity. If it is, add the player to a non-collision list in the Volume. I believe the Volumes (which can be used as a moving entity) have a collision override. Basically, if an object collides with the volume, check to see if that object is on the non-collision list. If so, ignore the collision. If not, collide as per-usual.

You might be able to avoid the non-collision list entirely though and just call a function in the Volume when you get the reference to it from the Trace in commandDrop.

It has been awhile since I've touched UnrealScript though but from what I do remember, this is very possible.

Another solution would be to use the trace in the commandDrop function of the player controller and find the height/width of the colliding volume. You could then change the players location to just below the volume. For visuals, you'd have to set a maximum height for the Volume though, but if it was small enough, the small player stutter probably wouldn't be noticeable. You could also add a drop effect to make it unnoticeable. Like for example, an effect similar to Captain Falcon's "Falcon Punch" in the Super Smash Bros series.
> 2 votes

# Answer
If you could give these platforms a physics volume (not sure if this is exactly correct) that can detect the components of the collision vector looking for a positive z component (seeing as positive z is up in UDK by default) then allow that player to pass throw.

On the falling through on `commandX` you would have to be able to relay a message containing the command (or a bool), and the "player" to the volume, and then basically turn off collision for that player for 1-2 seconds.

I am unsure on absolute implementation of these features.
> 1 votes

# Answer
The way to implement this in a general sense with a "real physics engine" is to add an OnInitialCollision handler that sets an IgnoreCollision flag on the pair of objects if the player hits the platform from below or the sides.

If the player wants to drop through platforms, set a flag on him and always ignore the platform collisions if the flag is set. You can set the flag so log as the player is pushing down, set it when pushing down and clearing it next frame, or whatever other behavior you want.

I don't know if UDK supports this. I tried to Google some info for you, but came up empty handed. There is a Touch event in UDK, but I couldn't find out if that can be used for collision filtering or not.

You may have to toggle collision layers instead of filtering specific collision pairs. Toggle the player, rather than the platforms, to keep things working in multiplayer. You will need to avoid a few specific level design possibilities with this approach, such as having two platforms close enough together that the player could touch both. That probably isn't something you want anyway, but it's worth being aware of.
> 1 votes

---
Tags: udk, platformer
---


# Question
Title: Moving Unit Parallel to Mouse in TBS Game
I'm writing a basic Turn-Based Strategy game using Unity3D. It's not grid-based. I've come to the point where I'm coding unit movement, and I'm having trouble figuring out how far to move the units based on the mouse position. The following image is what I want:

The unit should snap forward along the red vector; it will always move in the direction it's facing. The reason I'm doing it this way is because I want the user to be able to see the result of their move, and I want to avoid some sort of GUI slider. The blue vector represents the vector from the mouse to the target point.

**So, to sum it up: how do I calculate the movement (red) vector, based on the unit and mouse positions? Pseudo-code would be great!**

# Answer
> 3 votes
It's not entirely clear, but I understand the unit will only be able to move in the direction it is facing. In that case you will need to factor that vector into the equation as well (next to the unit and mouse positions).

Have a look at the equations in Minimum Distance between a Point and a Line by Paul Bourke.

In this picture, your unit's position is `P1`, `P2` can be found by adding its facing vector to its position, and `P3` is the position of the mouse cursor. The point of intersection gives you the endpoint for the movement.

---
Tags: unity, vector, turn-based-strategy
---


title: Spritesheet per pixel collision XNA

text:
# Question
Title: Spritesheet per pixel collision XNA
So basically I'm using this:

```
 public bool IntersectPixels(Rectangle rectangleA, Color[] dataA,Rectangle rectangleB, Color[] dataB)
    {
        int top = Math.Max(rectangleA.Top, rectangleB.Top);
        int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
        int left = Math.Max(rectangleA.Left, rectangleB.Left);
        int right = Math.Min(rectangleA.Right, rectangleB.Right);
        for (int y = top; y < bottom; y++)
        {
            for (int x = left; x < right; x++)
            {
                Color colorA = dataA[(x - rectangleA.Left) + (y - rectangleA.Top) * rectangleA.Width];
                Color colorB = dataB[(x - rectangleB.Left) + (y - rectangleB.Top) * rectangleB.Width];
                if (colorA.A != 0 && colorB.A != 0)
                {
                    return true;
                }
            }
        }
        return false;
    }

```

In order to detect collision, but I'm unable to figure out how to use it with animated sprites.

This is my animation update method:

```
public void AnimUpdate(GameTime gameTime)
    {
        if (!animPaused)
        {
            animTimer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
            if (animTimer > animInterval)
            {
                currentFrame++;
                animTimer = 0f;
            }
            if (currentFrame > endFrame || endFrame <= currentFrame || currentFrame < startFrame)
            {
                currentFrame = startFrame;
            }
            objRect = new Rectangle(currentFrame * TextureWidth, frameRow * TextureHeight, TextureWidth, TextureHeight);
            origin = new Vector2(objRect.Width / 2, objRect.Height / 2);
        }
    }

```

Which works with multiple rows and columns.

and how I call the intersect:

```
    public bool IntersectPixels(Obj me, Vector2 pos, Obj o)
{
Rectangle collisionRect = new Rectangle(me.objRect.X, me.objRect.Y, me.objRect.Width, me.objRect.Height);
                    collisionRect.X += (int)pos.X;
                    collisionRect.Y += (int)pos.Y;
if (IntersectPixels(collisionRect, me.TextureData, o.objRect, o.TextureData))
{
    return true;
}
return false;

```

}

Now my guess is that I have to update the textureData everytime the frame changes, no? If so then I already tried it and miserably failed doing so

Any hints, advices?

If you need to see any more of my code just let me know and I'll update the question.

Updated almost functional collisionRect:

```
collisionRect = new Rectangle((int)me.Position.X, (int)me.Position.Y, me.Texture.Width / (int)((me.frameCount - 1) * me.TextureWidth), me.Texture.Height);

```

What it does now is "move" the block up 50%, shouldn't be too hard to figure out.

Update:

Alright, so here's a functional collision rectangle(besides the height issue)

```
collisionRect = new Rectangle((int)me.Position.X, (int)me.Position.Y, me.TextureWidth / (int)me.frameCount - 1, me.TextureHeight);

```

Now the problem is that it's still not getting the correct color values of the animated sprite.

So it detects properly but the color values are always:

R:0 G:0 B:0 A:0

↑↑↑ disregard that, it's not true after all.

For some reason now the collision area height is only 1 pixel..

# Answer
> 1 votes
It looks to me like you collide the wrong Rectangles. What you want for you collision rectangles for an object o is something like *o.Position* (a Vector2) plus the dimensions of its texture size:

*o.collisionRect = new Rectangle(o.Position.X, o.Position.Y, o.TextureWidth, o.TextureHeight)*

What you are currently taking as the collision rectangle is the *source rectangle*, the rectangle that tells you which part of the sprite sheet you want to draw for your current animation frame, which has nothing to do with your object's position:

```
objRect = new Rectangle(currentFrame * TextureWidth, frameRow * TextureHeight, TextureWidth, TextureHeight);

Rectangle collisionRect = new Rectangle(me.objRect.X, me.objRect.Y, me.objRect.Width, me.objRect.Height);
                collisionRect.X += (int)pos.X;
                collisionRect.Y += (int)pos.Y;

```

You also add a Vector2 pos, which you described in the comments as the object velocity vector, which would make even less sense; though by the name *pos* I guess you meant the right thing, the position vector, the object's location.

So you got it half right: the mistake was that you added that position vector to the sprite sheet source rectangle (which has varying X and Y values), instead of the object's dimensions (which, expressed as a rectangle, always has position (0, 0)).

Assuming your default, non-animated source rectangle is located at (0, 0) on the sprite sheet, it would explain why collision is working when not animated, because you happen to have a rectangle with the correct location, i.e. (0, 0). But as soon as you start animating, the X and Y coordinates are wrong, because you always need (0 + pos.X, 0 + pos.Y), but you get something other than 0, depending on your *currentFrame* and *frameRow*.

---
Tags: xna, collision-detection, sprites, spritesheet, pixel
---


# Question
Title: What do I need to reload after a device reset?
Is there a complete list of resources that need to be reloaded after a device reset? I want to make sure I'm not missing anything.

Also, should I reload them from disk each time, or do I want to make in-memory copies?

# Answer
> 8 votes
D3D11 does not have a "device lost" concept, at least not one like D3D9 had (with it's related "on-lost" and "on-reset" management).

DXGI, which you'll use with D3D10+, has error codes for the device being physically removed and one for a reset due to a bad command, but these require very different handling.

---
Tags: directx11
---


# Question
Title: How to place rooms proceduraly (rule based) on in a game word
I am trying to design the algorithm for my level generation which is a rule driven system. I have created all the rules for the system. I have taken care to insure that all rooms make sense in a grid type setup. for example: these rooms could make this configuration

The logic flow code that I have so far

```
Door{
    Vector3 position;
    POD orient;     // 5 possible values (up is not an option)
    bool Open;
}

Room{
    String roomRule;
    Vector3 roomPos;
    Vector3 dimensions;
    POD roomOrient;     // 4 possible values
    List doors<Door>;
}

LevelManager{
    float scale = 18f;
    List usedRooms<Room>;
    List openDoors<Door>
    bool Grid[][][];

    Room CreateRoom(String rule, Vector3 position, POD Orient){
        place recieved values
        based on rule fill in other data
    }

    Vector3 getDimenstions(String rule){
        return dimensions of the room
    }

    RotateRoom(POD rotateAmount){
        rotate all items in the room
    }

    MoveRoom(Room toBeMoved, POD orientataion, float distance){
        move the position of the room based on inputs
    }

    GenerateMap(Vector3 size, Vector3 start, Vector3 end){
        Grid = array[size.y][size.x][size.z];
        Room floatingRoom;
        floatingRoom = Room.CreateRoom(S01, start, rand(4));
        usedRooms.Add(floatingRoom);
        for each Door in floatingRoom.doors{
            openDoors.Add(door);
        }

//      fill used grid spaces

        floatingRoom = Room.CreateRoom(S02, end, rand(4);
        usedRooms.Add(floatingRoom);
        for each Door in floatingRoom.doors{
            openDoors.Add(door);
        }

        Vector3 nRoomLocation;
        Door workingDoor;
        string workingRoom;
//      fill used grid spaces

//      pick random door on the openDoors list
        workingDoor = /*randomDoor*/
//      get a random rule
        nRoomLocation = workingDoor.position;
//      then I'm lost
    }
}

```

I know that I have to make sure for convergence (namely the end is reachable), and to do this until there are no more doors on the `openDoors` list. right now I am simply trying to get this to work in 2D (there are rules that introduce 3D), but I am working on a presumption that a rigorous algorithm can be trivially extended to 3D.

EDIT: my thought pattern so far is to

1. take an existing open door
2. and then pick a random room (restrictions can be put in later)
3. place that room's center at the doors location
4. move the room in the direction of the doors orientation half the rooms dimension w/respect to that axis
5. then test against the 3D array to see if all the grid points are open, or have been used, or if there is even space to put the room (caseEdge)
6. if caseEdge (which can also occur in between rooms) then put the door on a `toBeClosed` list, and remove it from the open list (placing a wall or something there).
7. then to do some kind of test that both the start, and the goal are connected, and reachable from each other (each room has nodes for AI, but I don't want to "have" to pull those out to accomplish this).

but this logic has the problem for say the U, or L shaped rooms in my example, and then I also have a problem conceptually if the room needs to be rotated.

# Answer
> 2 votes
As I explained before, since there are already good algorithms to perform pathfinding, space filling etc, you could simplify the work by setting up the initial rooms.

Since it's a game world, the goal is not just to fill up a grid with rooms, but to create a space where a player can move around following a game logic.

So, if you set some rules to avoid breaking your world such as:

* Each door have its own properties (one-way, two-ways, locked, etc).
* A player can enter/exit a room only by a door.
* Each room must be 'solved': it must be possible, starting from any door, to reach each of the other doors in the room.
    + For each room, some particular rotations could be avoided to ensure the previous rule.
* Rooms are connected by doors, and connected doors must be of the same size.

By 'door' I mean any kind of passage. Even empty space can be a door.

Since these prerequisites are met per-room, you can create rooms as complex as you need because it won't affect your algorithm (the number of doors per room WILL affect the computing time).

I.E.: to avoid a corridor with a door on the end to become *vertical* and so requiring a huge jump/fall you can set those 2 rotation as off-limit. That way, when the filling algorithm tries to set that room, it will discard it if it would require that illegal rotation.

Also, if the player suddenly gains the ability to fly, it still won't affect your algorithm directly: it will affect the 'solving' ability for each room and the possible rotations.

After this setup, the case is similar to inventory-filling/pathfinding/maze solving, depending on what you actually need. Every time the algorithm choose a candidate solution, with a simple check to enforce previous rules you'll have it discard it or keep it, without modifying the algorithm itself.

I think that the possibility to rely on a solid external algorithm is a huge advantage over a custom-tailored one.

# Answer
> 0 votes
Rather than using your method, I would use a maze algorithm, like one of these:

Then just knock out sections of walls to make larger rooms. Make sense? You could probably create more diverse and interesting results this way, with faster compute speed.

---
Tags: algorithm, procedural-generation
---


# Question
Title: How do I properly use String literals for loading content?
I've been using verbatim string literals for some time now, and never quite thought about using a regular string literal until I started to come across them in Microsoft provided XNA samples. With that said, I'm trying to implement a new AudioManager class from the Net Rumble sample.

I have two (2) issues here:

**Question 1:** In my code for my GameplayScreen screen I have a folder location written as the following, and it works fine:

```
menuButton = content.Load<SoundEffect>(@"sfx/menuButton");
menuClose = content.Load<SoundEffect>(@"sfx/menuClose");

```

If you notice, you'll see that I'm using a verbatim string, with a forward slash "/".

In the AudioManager class, they use a regular string literal, but with two backslashes "\\". I understand that one is used as an escape, but why are they BACK instead of FORWARD? (See below)

```
soundList[soundName] = game.Content.Load<SoundEffect>("audio\\wav\\"+ soundName);

```

**Question 2:** I seem to be doing everything correctly in my AudioManager class, but I'm not sure of what this line means:

```
audioFileList = audioFolder.GetFiles("*.xnb");

```

I suppose that the \*xnb means look for everything **BUT** files that end in \*xnb? I can't figure out what I'm doing wrong with my file locations, as the sound effects are not playing. My code is not much different from what I've linked to above.

```
private AudioManager(Game game, DirectoryInfo audioDirectory) : base(game)
{
    try
    {
        audioFolder = audioDirectory;
        audioFileList = audioFolder.GetFiles("*.mp3");
        soundList = new Dictionary<string, SoundEffect>();

        for (int i = 0; i < audioFileList.Length; i++)
        {
            string soundName = Path.GetFileNameWithoutExtension(audioFileList[i].Name);
            soundList[soundName] = game.Content.Load<SoundEffect>(@"sfx\" + soundName);
            soundList[soundName].Name = soundName;
        }

        // Plays this track while the GameplayScreen is active
        soundtrack = game.Content.Load<Song>("boomer");
    }
    catch (NoAudioHardwareException)
    {
        // silently fall back to silence
    }
}

```

# Answer
> 7 votes
1. Different file systems use different delimiters between folders in paths. Unix/Linux based OSes use forward slashes. Windows generally uses backslashes however they also accept forward slashes. I personally use forward slashes but that's just out of habit since I spend some of my time on OS X.
2. GetFiles("\*.xnb") will be looking only for XNB files in that directory (see http://msdn.microsoft.com/en-us/library/8he88b63.aspx). Have you stepped through in the debugger to see what files it's finding, if any? When you create the AudioManager, how are you getting/creating that DirectoryInfo object? Is it pointing at the correct directory?

# Answer
> 1 votes
For question #1, the answer is that it doesn't really matter ... the path will work whether you use forward or backwards slashes. More specifically, the double backslash is because in a regular string the backslash is an escape character ... so if you want an actual backslash you have to use two of them (to escape the escape character). But if you use the verbatim string, you could do:

```
soundList[soundName] = game.Content.Load<SoundEffect>(@"audio\wav\"+ soundName);

```

the `*` character is a wild card ... so it means to list *only* files with the xnb extension

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


# Question
Title: Is it possible to generate Events and Hooks in Lua for any game without built-in support?
Does a game have to have built-in functions to accept and run lua scripts, or can I design Events and Hooks using Lua on any game I please, akin to the days where C code could be used to hook into the WinAPI using dlls?

The reason I ask is, I am trying to create a background application that will perform events and hooks on a particular game that does not currently support lua in-game.

Brief examples:

Events: \- An action executed by the PLAYER is detected. For instance, hitting the Q key will normally make my character use an ability, but with my Lua script running in the background, will cause a sound to play on my computer (or something).

Hooks: \- An action within the GAME is detected. For instance, the game spawns an enemy every minute. When an enemy spawns, the script will detect this and perform an action, for instance playing a sound locally on the computer.

I would like to do both, but I know for games like Garry's Mod, the game already has built-in support for running lua scripts.

Is there a way to do either events OR hooks using lua similarly to how C/C++ can connect to a game using WinAPI dlls?

# Answer
> 3 votes
Lua is not *magic*. Lua cannot magically associate itself with any application and interfere in any function call.

You can't even do that from C. Yes, with Win32 DLL injection, you can interpose a DLL within a DLL boundary. But if there is no DLL boundary to inject your code... you can't do anything. And I'm guessing most games don't expose the "spawn entity" function across a DLL boundary.

In general, most games put the main game code either in a DLL by itself or within the executable itself. The graphics system, sound system, etc, may be DLLs. But even if the game code is a DLL, internal game processes (create entity, manage entity, etc, stuff you want to hook to) would all be internal within that DLL. And therefore not injectable.

Oh, you *can* do this (not with Lua directly). But you would have to decompile the application, reverse-engineer the flow of functions and such, and manually edit the compiled binaries to add your external hook functions.

# Answer
> 0 votes
I did a similar thing with Just Cause 2 using the WinAPI, I used cheat engine to find out where the players position was stored in memory and networked that to my iphone to display a 'GPS'.

You can see the code here: https://github.com/perky/JC2-GPS

I don't know about accessing memory from Lua but cheatengine seems to use Lua, it's worth taking a look: http://www.cheatengine.org/

---
Tags: lua, events
---


title: Rotation angle based on touch move

text:
# Question
Title: Rotation angle based on touch move
I want to rotate my stick based on the movement of the touch on the screen. From my calculation I did not able to find correct angle in degree. So please provide guidance, my code snippet for that are below.

```
if (pSceneTouchEvent.isActionMove()) {
    pValueX = pSceneTouchEvent.getX();
    pValueY = CAMERA_HEIGHT - pSceneTouchEvent.getY();
    rotationAngle = (float) Math.atan2(pValueX, pValueY);
    stick.setRotation((float) MathUtils.radToDeg(rotationAngle));

}

```

# Answer
> 2 votes
The answer for the above question is as below

```
    if (pSceneTouchEvent.isActionMove()) {

        pValueX = pSceneTouchEvent.getX();
        pValueY = CAMERA_HEIGHT - pSceneTouchEvent.getY();

        directionX = pValueX - stick.getX();
        directionY = (CAMERA_HEIGHT - pValueY) - stick.getY();

        rotationAngle = (float) Math.atan2(directionY, directionX);

        stick.setRotation(MathUtils.radToDeg(rotationAngle));

    }

```

# Answer
> 5 votes
**I'm assuming you're talking about a joystick; one which, when active, always points toward your finger.**

It looks like your X and Y values are positions *relative to one corner of the screen* \- so you're just measuring the angle from one corner of the screen to your finger. Of course it would never work! Well, unless your stick is on the corner of the screen.

What you need to do find the angle of the player's finger *relative to your joystick's position*.

In Vector mathematics: `the vector from B to A = A - B`

So in your case: `the vector from Stick to Touch = Touch - Stick`

```
// where joyX and joyY are the position of the joystick on the screen
touchX = pSceneTouchEvent.getX();
touchY = CAMERA_HEIGHT - pSceneTouchEvent.getY();
directionX = touchX - joyX
directionY = touchY - joyY
rotationAngle = (float) Math.atan2(directionY, directionX);

```

---
Tags: andengine
---


title: Circular class dependency

text:
# Question
Title: Circular class dependency
Is it bad design to have 2 classes which need each other?

I'm writing a small game in which I have a `GameEngine` class which has got a few `GameState` objects. To access several rendering methods, these `GameState` objects also need to know the `GameEngine` class - so it's a circular dependency.

Would you call this bad design? I am just asking, because I am not quite sure and at this time I am still able to refactor these things.

# Answer
> 0 votes
It's not a bad design by nature, but it can easily get out of control. In fact you are using that design in your everyday codes. For example vector knows it's first iterator and iterators have pointer to their container.

Now in your case, it's much more better to have two separate classes for GameEnigne and GameState. Since basically those two are doing different things, and later you might define lots of classes which inherit GameState (like a GameState for each scene in your game). And no one can deny their need to have access to each other. Basically GameEngine is running gamestates, so it should have a pointer to them. And GameState are using resources defined in GameEngine (like rendered, physics manager, etc.).

You can't and shouldn't combine those two classes into each other either since they are doing different things by nature and combining will result in a very big class which no one likes.

So far we know that we need circular dependency in out design. There are multiple ways to create that safely:

1. As you suggested we can put a pointer of each of them into another, it's the most simple solution but might easily get out of control.
2. You can also use singleton/multiton design, with this method you should define your GameEngine class as a singleton and each of those GameStates as a multiton. Though many of developers consider both singleton and multiton to be AntiPattern I prefer this kinda design.
3. You can use global variables, hey are basically same thing as Singleton/multiton but they a slight difference in the fac that they don' limit the programmer no to create instances at will.

To conclude his answer you might use any of those three methods but you need to be careful not to over use either of them since as I said all those designs are really dangerous and might easily result in a unmaintainable code.

# Answer
> 6 votes
> Is it bad design to have 2 classes which need each other?

It's a bit of a *Code Smell*, but one can leave with it. If that's the easier and faster way to get your game up and running, go for it. But keep that in mind because there's a good chance you'll have to refactor it at some point.

The thing with C++ is that circular dependencies won't compile so easily, so it might be a better idea to get rid of them instead of spending time fixing your compilation.

See this question on SO for a few more opinions.

> Would you call \[my design\] bad design?

Nope, it's still better than putting everything in one class.

It's not so great, but it's actually quite close to most implementations I've seen. Usually, you'd have a manager class for game states (beware!), and a renderer class, and it's quite common that they are singletons. So the circular dependency is "hidden", but it's *potentially* there.

Also, as you were told in comments, it's a bit weird that game state classes perform some kind of rendering. They should just hold state information, and rendering should be handled by a renderer, or some graphic component of game objects themselves.

Now there might be **the ultimate** design. I'm curious to see if other answers bring one nice idea. Still, you are probably the one that can find the best design for your game.

# Answer
> 6 votes
It's often considered bad design to have to have 2 classes that directly refer to each other, yes. In practical terms it can be harder to follow the control flow through the code, the ownership of objects and their lifetime can be complicated, it means that neither class is reusable without the other one, it could mean that control flow should really live outside both of these classes in a third 'mediator' class, and so on.

However, it's very common for 2 *objects* to refer to each other, and the difference here is that usually the relationship in one direction is more abstract. For example, in a Model-View-Controller system, the View object may hold a reference to the Model object, and will know all about it, being able to access all its methods and properties so that the View can populate itself with relevant data. The Model object may hold a reference back to the View so that it can make the View update when its own data has changed. But rather than the Model having a View reference - which would make the Model dependent on the View - usually the View implements an Observable interface, often with just 1 `Update()` function, and the Model holds a reference to an Observable object, which may be a View. When the Model changes, it calls `Update()` on all its Observables, and the View implements `Update()` by calling back into the Model and retrieving any updated information. The benefit here is that the Model doesn't know anything about Views at all (and why should it?), and can be re-used in other situations, even those without Views.

You have a similar situation in your game. The GameEngine will normally know about GameStates. But the GameState doesn't need to know all about the GameEngine - it just needs access to certain rendering methods on the GameEngine. That should set off a little alarm in your head that says that either (a) GameEngine is trying to do too many things within one class, and/or (b) GameState doesn't need the whole game engine, just the renderable part.

Three approaches to resolving this include:

* Make GameEngine derive from a Renderable interface, and pass that reference into the GameState. If you ever refactor the rendering part out, you just have to ensure it keeps the same interface.
* Factor out the rendering part into a new Renderer object, and pass that to GameStates instead.
* Leave it as it is. Maybe at some point you'll want to access all the GameEngine functionality from GameState, after all. But do bear in mind that software that is easy to maintain and easy to extend usually requires that each class refers to as little on the outside as possible, which is why breaking things up into sub-objects and interfaces that perform a single and well-defined task is preferable.

# Answer
> 0 votes
It is generally perceived to be good practice to have high cohesion with low coupling. Here are a few links regarding coupling and cohesion.

wikipedia coupling

wikipedia cohesion

low coupling, high cohesion

stackoverflow on best practice

Having two classes reference each other is having high coupling. The google guice framework aims to achieve high cohesion with low coupling through means of dependency injection. I would suggest you read up on the topic a bit more and then make your own call given your context.

---
Tags: c++, architecture
---


# Question
Title: Power Distribution amongst connected nodes
In my game the map is represented by connected nodes, each node has a number of connected nodes. The nodes represent a system in which players can build structures and move units about. If you're familiar with Sins of a Solar Empire the game map is very similar.

I want each node to be able to produce power and share it with all connected nodes. For example if A, B, C & D are all connected and produce 100 power units, then each system should have 400 power units available. If node B builds a structure that consumes 100 power units then A, B, C & D should then have 300 power units available.

I've been working on this system all day and haven't been able to get it working quite the way I want.

My current implementation is to first recurse through each nodes's connected node adding up the power, I keep a list of closed nodes so it doesn't loop, it's quite similar to A\* actually.

Pseudo code: All nodes start with the properties

```
node.power = 0
node.basePower = 100 // could be different for each node.
node.initialPower = node.basePower

```

-

```
function propagatePower( node, initialPower, closedNodes )
  node.power += initialPower
  add( closedNodes, node )
  connectedNodes = connected_nodes_except_from( closedNodes )
  foreach node in connectedNodes do
     propagatePower( node, initialPower, closedNodes )
  end
end

```

After this I iterate through all power consumers.

```
foreach consumer in consumers do
   node = consumer.parentNode
   if node.power >= consumer.powerConsumption then
     consumer.powerConsumed += consumer.powerConsumption
     node.producedPower -= consumer.powerConsumption
   end
end

```

Then I adjust the initial power for the next propagation cycle.

```
foreach node in nodes do
   node.initialPower = node.basePower - node.producedPower
   node.displayPower = node.power // for rendering the power.
   node.power = 0
end

```

This seemed to work at first but then I came into a problem.

* Say two nodes A & B produce 100Pu each, it's shared so both A & B have 200Pu.
* I then make two structures that consume 80Pu each on A (160Pu).
* Then the nodes power is adjusted to basePower - producedPower (100-160 = -60).
* Nodes are propagated, both nodes now have 40Pu (A: -60 + B: 100 = 40).
* Which is correct because they started with 200Pu - 160Pu = 40Pu.
* However now `node.power >= consumer.powerConsumption` is false.
* Whats worse is it's false for any structure that uses more that 40Pu, so the whole system goes down.

I could deduct from `consumer.powerConsumption` but what do I do if power is reduced elsewhere? I don't have the correct data to perform the necessary checks.

It's late so I'm probably not thinking straight but I thought to ask on here to see if anyone has any other implementations, better or worse I'd be interested to know.

# Answer
> 4 votes
Hm, I think you are making it too complicated.

Your nodes can either be producing power or consuming it. And they can either have enough power or not. So can I suggest just having a single "power" variable and +ve is producing power and -ve is consuming it. Then you can calculate how much power each connected node needs with:

(pseudo-code, sorry I don't know lua)

```
node {
    int id;
    int power;
    node_list children; // This assumes a stingily linked list
}

node_list root_nodes;

// Gather a list of all unique connected nodes
void gather_nodes( node root, list & node_list )

    // Check the node is not in the list already
    is_already_in_list = false
    for node_in_list in node_list:
        if node_in_list.id == root.id
            is_already_in_list = true;
    if( !is_already_in_list )
        node_list.push_back( root )

    // iterate over the children and add them to the list
    for child in root.children:
        gather_nodes( child, node_list )

for n in root_nodes:
    int overall_power = 0;
    node_list nodes;
    gather_nodes( n, nodes )

    // Calculate the power
    for connected_node in nodes:
        overall_power += connected_node.power;

    // If overall_power is +ve then all connected_nodes have enough power
    // otherwise all connected_nodes do not have enough power

```

And of course you only need to recalcuate this when the power changes or you add/remove a node.

---
Tags: lua, distribution
---


# Question
Title: Exporting the frames in a Flash CS5.5 animation and possibly creating the spritesheet
Some time ago, I asked a question here to know what would be the best way to create animations when making an Android game and I got great answers.

I did what people told me there by exporting each frame from a Flash animation manually and creating the spritesheet also manually and it was very tedious.

Now, I changed project and this one is going to contain a lot more animations and I feel like there has to be a better way to to export each frame individually and possibly create my spritesheets in an automated manner.

My designer is using Flash CS5.5 and I was wondering if all of this was possible, as I can't find an option or code examples on how to save each frame individually.

If this is not possible using Flash, please recommend me another program that can be used to create animations without having to create each frame on its own. I'd rather keep Flash as my designer knows how to use it and it's giving great results.

# Answer
> 3 votes
First of all, let me say that there's absolutely no need to build your sprite-sheets manually. There are some very good tools for this purpose. Also exporting animations from Flash should be easy and straight-forward. Here's how you do it:

You can export your animations by selecting `File` \> `Export` \> `Export Movie...`. Then you select `PNG Sequence` as format and it will export to a series of PNG files.

Then you can head over to this question where you'll find lots of good answers on how to create sprite-sheets from these PNGs.

Flash CS6 will have a feature to directly export animations to sprite-sheets. Older versions will have to use the procedure outlined above.

# Answer
> 2 votes
There's a tool called SWFSheet specifically intended for that purpose, but personally I prefer the approach bummzack explained, of exporting the frames to a PNG sequence and then using a tool like TexturePacker to generate a spritesheet from the folder of images. The workflow is much more flexible that way, and the sprite packing abilities of a dedicated tool are better.

---
Tags: animation, flash, sprites, spritesheet
---


# Question
Title: How can I implement 2D cel shading in XNA?
So I was just wondering on how to give a scene I am rendering a hand drawn look (like say Crayon Physics). I don't really want to preprocess the sprites and was thinking of using a shader. Cel shading supplies the effect I want to achieve, but I am only aware of the 3D instances for it.

So I wanted to ask if anyone knew a way to get this effect in 2D, or if cel shading would work just as fine on 2D scenes?

Edit:The reason why i didn't want to do preprocessing ,was that i almost don't have anything to prepossess.I have some material textures ,which are basically just black and white images and using them i create textures from specific vertices ,which represent entities in the game (mostly physics based ones).So i wasn't sure how to processes the textures for the texture mapping to work as i intended.Thanks for the help!

# Answer
> 6 votes
You can't really do it without some kind of preprocessing step -- either authoring the original sprites so they have the desired effect, or including some extra information along with each sprite about pixel "depths" and normal information, essentially turning your 2D sprite into a 3D-ish data structure.

The cel shading effect is designed to make 3D art look like hand-drawn 2D art. It works with the principle of color quantization, most of the time -- mapping a smooth continuous input range into one of N discrete color buckets. Usually the diffuse term of your lighting equation -- the "n-dot-l" term, or the dot product between a vertex normal and the light vector -- is used at the input because this will range smoothly from 0 to 1. You can use this as input to a 1D texture read where the texture contains information about the actual color to apply. It usually is just a band of a small number of discrete colors.

Obviously this will be hard to do without that input value, and without encoding additional information -- such as pixel normals or depth (with which you could in theory reproduce the normals at runtime) -- into the sprite you won't have any meaningful data to use as the input. Unless your sprites are being authored in a 3D modelling program where you might be able to write some export script for producing the final renders with encoded normal information (like a normal map, essentially), you are likely better off just drawing the sprites to look the way you want.

The closest you could probably get would be to write a shader that maps the \[0..1\] range of every color component into one of a fixed set of buckets -- say 0, 0.25, 0.5, 0.75 and 1. This could be done independently for each component or on a global basis. It essentially massively reduces the color space available to your sprites, which is more-or-less what cel shading does. But unless your sprites are authored to account for this it's entirely possible that you will spend hours tweaking the mapping and still end up with sprites that look hideous in practice.

A render effect that is typically applied with cel shading is feature edge detection and rendering -- "outline" rendering. It would be possible to do this with 2D sprites, but you'd only get the outlines of the sprites and no interior feature edges, which does not look nearly as good. Once again, to achieve a better effect you'd be preprocessing the sprite data or just authoring the edges directly into the sprite images.

---
Tags: xna, 2d, shaders
---


title: Box2d debug render

text:
# Question
Title: Box2d debug render
How can I render the body and joints in the physics world? During research I found the class called Box2dDebugRenderer. But when I put it into use it was full of errors. I do not found some classed in it. My basic requirement is to draw a body that were available in the physics world. Please provide some guidance on that. Also provide any other view about that.

# Answer
With my limited experience with physics engines, the developer is required to implement their own drawing code for that the physics engine then uses for debug drawing.

It's usually broken down into simple methods for you to implement like `line(float startX, float startY, float endX, float endY)`, where you need to implement the functionality to draw the line specified. This might be the reason for it being "full of errors", but without more information it's hard to tell.

You can take a look at libgdx to see how it's been implemented there. And look into the `ShapeRenderer` they employ here.
> 2 votes

# Answer
What version of AndEngine are you using? GLES1 or GLES2? It is likely that you are trying to use an outdated version.

If GLES1, the code here works just fine. I linked it to my GLES1 project today.

I you use GLES2, there is a thread about it over at the AndEngine forums.

Please note that using this will make your app run quite slow.
> 2 votes

---
Tags: box2d, andengine
---


title: How to make a beam follow a path in xna

text:
# Question
Title: How to make a beam follow a path in xna
I'm making a 2D shmup with XNA 4.0 and one of the weapons in the game that I want is a laser beam that follows a path or a series of points and will smoothly beam along the path.

How would I go about achieving this?

# Answer
Try using a `Queue` of (x,y) coordinates. I don't know if you'll need to do it dynamically or at compile time, but you should be able to figure something out either way.

Are you wanting the laser to follow curves as well, or just connect the dots? If its the first option, you're gonna need to do some math too.
> 2 votes

---
Tags: xna, 2d
---


# Question
Title: Fitting Android game to different screen sizes
I am making an Android game that is only in portrait screen orientation. It works great when I run it on my phone, but when I run it on a tablet, even though the screen size is bigger, all of the bitmaps are the same size. Is there any way to make the bitmaps stay the same proportion even on different size screens?

# Answer
> 11 votes
Unless you're using AbsoluteLayout (Usually a very bad idea, as you design your layout using x/y coordinates, which will only suit the device it's been designed on) this should not happen - Android applications automatically adjust to the device's screen-size. However from what you describe (Layout does not adjust to Table Screen), it sounds like AbsoluteLayout might be the issue here.

Make sure that in your layout XML files you're NOT using absolute layouts (this includes setting explicit coordinates/widths/heights on any kind of View). Instead consider using:

* LinearLayout \- Stacks multiple views horizontally or vertically
* FrameLayout \- Usually contains one Child
* RelativeLayout \- Align children relative to each other
* TableLayout \- A Table-based layout
* ScrollView \- May contain one child item (such as a LinearLayout) and lets you scroll it's content

... whatever best suits your purpose.

**If you're new to Android**, then Google offers a nice tutorial that introduces to the different Layout Types mentioned above. More tutorials can be found here.

Furthermore your API Level would be relevant (to know whether you're using Android 2.x or 4.x - I don't assume 3.x as it's not available for Smartphones) to figure out the cause of your issue.

Are you forcing your Application into Portrait mode by setting:

```
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set screen orientation for this dialog to portrait
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

```

... in your Activity that displays the game's views?

Please provide more info on how you're layouting your views (are you using XML for the layout that you later inflate in your Activity, or are you using in-code layouting in your Activity etc....) ? Furthermore: Did you try running your app in a Smartphone - and Tablet-sized Emulator? If yes, does the issue persist?

---

**UPDATE: HOW TO SCALE BITMAPS**

The OP asked how he can scale the bitmap's he's using in his game. One option (from all I know about the OP's setup): The SurfaceHolder.Callback that you're overriding to display your game and on which you render all the Bitmaps etc... has a method called:

```
surfaceChanged(SurfaceHolder holder, int format, int width, int height)

```

That method gives you the width/height of your surface, so you could now use:

```
Bitmap.createScaledBitmap (Bitmap src, int dstWidth, int dstHeight, boolean filter)

```

from the Bitmap class. To resize your images in proportion to the size of the surface you're drawing onto.

What you need to do is this: If you know the dimensions of your bitmap in relation to a given screensize, for instance the screen-size of your smartphone. Then you can calculate the target dimensions of the scaled bitmaps. Here is the math (wrapped in an example):

Say you have a **Bitmap A** with the dimensions **25x50 (widthxheight)** which is displayed on a screen with the dimensions 100x200 (widthxheight). For that screen size (100x200) the bitmap has the correct dimensions - now if you want to display the bitmap on a larger screen you need to:

* Calculate the scale factor for the bitmap size
* Maintain the aspect ratio of the bitmap (so it does not get distorted)

Say the larger screen is 200x300 (widthxheight) then the scale-factor for the width is:

```
200(target screen width)/100(default screen width) = 2

```

So **2** is our scale-factor for the width and height value of the bitmap, since we need to maintain the aspect ratio of the bitmap, we can simply multiply the scale factor with the width and height of the bitmap:

```
bitmapWidth * 2 = scaledBitmapWidth
bitmapHeight * 2 = scaledBitmapHeight

```

So using our example bitmap A from above and the mentioned formula, the new dimensions of the bitmap would be: 50x100 (widthxheight) because:

```
 2*25(width) = 50 height
 2*50(height) = 100 height

```

Soo now that we know the new size of our bitmap we simply use the API call I mentioned above and fill in the blanks:

```
   Bitmap.createScaledBitmap (myBitmap, 50, 100, false)

```

myBitmap in the above example is the original bitmap A that had the dimensions 25x50 and is scaled to 50x100 using the above code-snippet.

---

**However** \- this wouldn't solve your original issue of the application taking up only the upper right corner of a tablet-sized device. To answer that one we'd require answers to the questions we asked you regarding your setup. I'll quickly sum them up here:

* Are you using a game-engine such as AndEngine or Unity ?
* Are you writing your layout in xml? If yes, what's your root-layout for rendering your your game content?
* You mentioned that you're implementing SurfaceHolder.Callback? The width/height provided in the method call of surfaceChanged gives you the size of the surface - is it the same size when your app runs on a smartphone or a tablet?
* Do you have any access to the SurfaceView (or whatever is linked to that SurfaceHolder.Callback you're implementing), so we could determine if that's the one rigidly setting the app size to smartphone size.
* Do the same resize-issues occur in the emulator with different screen resolutions?

A general suspicion: Not every smartphone has the same screen size, in fact there's a wide range of screen sizes, which makes me wonder: Did u ever test your app on a smartphone with a different screen size than your screen? Because - the fact that it fits your screen, but not a tablet, makes me wonder who sets those dimensions and when. Because I doubt that an app can adjust to all smartphone-screen-sizes, but not to tablet sizes - won't make much sense (because they more or less have the same android core running on them, some differences between s.x, 3.x and 4.x aside) UNLESS you're using a framework which does not support (for whatever reason - maybe you'd have to buy tablet support extra or whatever) tablet-sized screen sizes. That's why it's really important to know, whether the app resizes properly on your phone only, or on other smartphones as well. The only way I am aware of how an app can be limited to the screen size of one specific phone is by using AbsoluteLayout and generally absolute dimensions for widgets etc...

---

**UPDATE: Scaling x/y Coordinates**

In order to adjust your bitmap's location to the screen size, something like the following should do the job:

* Screen dimensions: 100/200 (width/height)
* Bitmap location: x=50/y=100

Now, if you increase the screen size, you'd have to scale those x/y values along:

* Screen dimensions: 200/400 (width/height)

The scale factor would be 2, because the width and height equally increased by two. Hence the dimensions would be...

* Bitmap location: x=100/y=200

Another try - this time with different scale factors for width/height

* Screen dimensions: 100/150 (width/height)
* Bitmap location: x=50/y=50

If the new target screen is 150/250 then calculations are:

* Scale factor for width = targetWidth / originalWidth = 1.5
* Scale factor for height = targetHeight / originalHeight = 1.666... (Period)

Now we need to scale the x/y coordinates, x is scaled using the width-scale and height is scaled using the height-scale, here's the result:

* x = originalX * 1.5 = 75
* y = originalY * 1.666.. (Period) = 83.333... (Period)

So the new screen dimensions and the scaled x/y coordinates are:

* width = 150
* height = 250
* x = 75
* y = 83,333... (Period)

To make a long story short, the algorithm for scaling bitmaps is:

```
X = (targetScreenWidth / defaultScreenWidth) * defaultXCoordinate
Y = (targetScreenHeight / defaultScreenHeight) * defaultYCoordinate

```

# Answer
> 3 votes
There is a good and relevant article on Android.com : http://developer.android.com/guide/practices/screens\_support.html

This reference helps you sort through screen size, screen density, and resolution. The goal is to use the Android APIs to achieve "density independence" so that your user interface components and graphics can look good on various devices.

Remember that you can also create different configurations of Android Virtual Devices for the emulator while you're testing layout and appearance: http://developer.android.com/guide/developing/devices/emulator.html

# Answer
> 0 votes
Just a shot in the dark here. Have you set whatever the master layout is to fill parent both vertically and horizontally?

---
Tags: java, android, screen
---


# Question
Title: Cross-platform builds with OGRE3D via CMake. Any tips?
I've been trying to compile a simple project for both OSX and Windows platforms, using OGRE3D, but I've got some problems on the way.

I'm using CMake to create my platform specific project files (VS solution & Xcode project). Some problems I found are:

* OGRE3D source is distributed in 2 flavors, Windows sources and UNIX/OSX sources.
* In OSX, compiling dependencies (freetype, FreeImage and specially OIS) is such a pain.
* I don't know how to handle precompiled dependencies (they exist for both Win & Mac).

May sound like a noob question, but I would appreciate some tips on this. Resources, forum posts, anything. There exists any "cross-platform base project for OGRE3D" on the net? Would be really helpful if someone who already managed to do this can bring some light.

Btw, I'm not basing the project on OGRE3D, it's just that is the biggest library I'm probably using, so I depend a lot on it.

# Answer
CMake should take care of everything once it's completely configured and found the precompiled dependencies.

Ogre's CMake system will look for the dependencies when run to generate the project files to build the library. If the dependencies are not installed (see here) you can specify where the precompiled dependencies are to be found in the flags from the CMakeGUI (I don't remember exactly and can't check right now, sorry). They will end with INCLUDE\_DIR and LIB\_DIR and there will appear the dependency name BOOST, TBB, POCO, DEVIL...

Here you will find the rest of the instructions to build the latest Ogre in OSX.

Hope it helps you.
> 2 votes

---
Tags: ogre, cross-platform
---


# Question
Title: Tile map collision is not working properly
I am having problems setting collision between my sprite and the tiles. I have only done the code for colision for moving upwards but some places on the map it moves up and some places it doesn't.

Here is what I have so far:

```
Vector2 position;
private static float scalingFactor = 32;

static int tileWidth = 32;
static int tileHeight = 32;

int[ , ] map = {
                        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, },
                        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, },
                        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, },
                        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
                        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
                        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
                        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
                        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
                        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
                        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
                        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
                        {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, },
                        {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
                        {0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
                        {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
                        {0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
                        {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
                        {0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
                        {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
                   };

```

// This is in turtle.update

```
if ( keyboardState.IsKeyDown( Keys.Up ) )
{
    if ( position.Y > screenHeight / 4 )
    {
        //// current position of the turtle on the tiles
        int mapX = ( int )( position.X / scalingFactor );
        int mapY = ( int )( position.Y / scalingFactor ) - 1;

        if ( isMovable( mapX , mapY , map ) )
        {
            position.Y = position.Y - scalingFactor;
        }
    }
    else
    {
        MoveUp();
    }
}

private void MoveUp()
{
    motion.Y = -1;
}

public bool isMovable( int mapX , int mapY , int[ , ] map )
{
    if ( mapX < 0 || mapX > 19 || mapY < 0 || mapY > 20 )
    {
        return false;
    }
    int tile = map[ mapX , mapY ];
    if ( tile == 0 )
    {
        return false;
    }

    return true;
}

protected override void Update( GameTime gameTime )
{
    turtle.Update( screenHeight , scalingFactor , map );
    base.Update( gameTime );
}

```

EDIT: What i have tried to do is get the postion of my sprite and over which tile it is, then check whether the next tile is a path or a wall.

# Answer
No problem with being new to game development. You just need to make sure to provide enough information so that we can properly help you. Your on the right track with your code and it looks like your `isMoveable()` function is sound. I'm not sure what the difference between `motion.Y` and `position.y` are and why you're setting one vs the other depending on `position.Y > screenHeight / 4`, so the following maybe isn't what you want to achieve. However, I would suggest this simple structure for moving your character around.

```
// current position of the turtle on the tiles
int mapX = (int)(position.X / scalingFactor);
int mapY = (int)(position.Y / scalingFactor);
if (keyboardState.IsKeyDown(Keys.Up))
{
    if (isMovable(mapX, mapY-1, map))
    {
        position.Y = position.Y - scalingFactor;
    }
} else if (keyboardState.IsKeyDown(Keys.Down))
{
    if (isMovable(mapX, mapY+1, map))
    {
        position.Y = position.Y + scalingFactor;
    }
} else if (keyboardState.IsKeyDown(Keys.Right))
{
    if (isMovable(mapX+1, mapY, map))
    {
        position.X = position.X + scalingFactor;
    }
} else if (keyboardState.IsKeyDown(Keys.Left))
{
    if (isMovable(mapX-1, mapY, map))
    {
        position.X = position.X - scalingFactor;
    }
}

```

*EDIT*

This could be because of the way you're indexing into the map. Note orientation for your map as defined in code is not the way it will display on screen. You're indexing into it like this:

```
int tile = map[ mapX , mapY ];

```

So `mapX` is referencing the rows of your array and `mapY` is referencing the columns. So the top row of tiles on your screen from left to right are referencing the last column in your array from top to bottom.
> 1 votes

# Answer
This looks suspect as I presume tile zero indicate movable and yet you return false

```
if ( tile == 0 )
{
    return false;
}

```
> 0 votes

---
Tags: xna, c#, collision-detection, tilemap
---