title: OBB collisions in Buildings

text:
# Question
Title: OBB collisions in Buildings
So I decided on using OBB as the main collision detection in my 3D game but I started to wonder how OBB can be used to detect collisions if a player is in a building, an object you can walk into. Should the building object be broken up into dozens of OBBs or is there like an OBB to mesh check I can do. Or maybe there's some other better way of doing this.

Thanks for the help guys.

# Answer
Split the building into more basic forms (walls, platforms, etc.) and also create a bounding box for the whole building. So, unless your tested object collides with the bounding box, you ignore everything being inside. Depending on the complexity you can group this even further, e.g. by building, by floor, by room, etc. Once you're sure you're indeed colliding with something small, like a char or table, you can check the actual faces of the object to determine collisions.

This way you can ensure lots of details (like windows or gaps you can shoot through) while still keeping the overall complexity of most comparisons low.
> 2 votes

---
Tags: c++, 3d
---


# Question
Title: Tetris - Rotations using Linear Algebra (Rotation Matrices)
I'm making Tetris in Java and am at the point of rotations... Originally I was hardcoding each rotation:

```
if (direction.equals("right")) {
            if (shape.equals("Bar")) {
                if (rotationsCounter == 0) {
                    currXs[0] += 1;
                    currYs[0] += -1;

                    currXs[1] += 0;
                    currYs[1] += 0;

                    currXs[2] += -1;
                    currYs[2] += 1;

                    currXs[3] += -2;
                    currYs[3] += 2;

                    rightRotate1 = new int[] {currXs[0], currYs[0], currXs[1], currYs[1], currXs[2], currYs[2], currXs[3], currYs[3]};
                }
                if (rotationsCounter == 1) {
                     etc...

```

Then, I have this to set the correct coordinates based on what the rotated counter is

```
   if (direction == "right") {
            if (shape == "Bar") {
                if (rotationsCounter == 0) {
                    pieceRotations = rightRotate1;
                }
                if (rotationsCounter == 1) {
                    pieceRotations = rightRotate2;
                }
                if (rotationsCounter == 2) {
                    pieceRotations = rightRotate3;
                }
                if (rotationsCounter == 3) {
                    pieceRotations = rightRotate0;
                }
            }
        }
        if (direction == "left") {
            if (shape == "Bar") {
                if (rotationsCounter == 0) {
                    pieceRotations = leftRotate3;
                }
                if (rotationsCounter == 3) {
                    pieceRotations = leftRotate2;
                }
                if (rotationsCounter == 2) {
                    pieceRotations = leftRotate1;
                }
                if (rotationsCounter == 1) {
                    pieceRotations = leftRotate0;
                }
            }
        }
        return pieceRotations;

```

But found that was a very tedious way to go...

People suggested I use rotation matrices in Linear Algebra.

So I tried rotating 1 coordinate in a Tetris piece just to see if I was doing it correctly... the point (1, 1) seems to rotate just fine...

So then I thought that the way to rotate the whole block was to get all the coordinates of each tile in a Piece (4 tiles, 16 coordinates), and rotate each one... but I was wrong.

**So my questions is...**

In the first picture, I choose (1, 1) as my rotation axis... How do I move the rest of the coordinates in relation to that point?

Thanks!

# Answer
> 6 votes
This answer still ignores the attempt to use matrix rotation, but I realized that there was a simple ***yet general*** solution.

First, assuming that the shape is encoded as coordinates of blocks in a grid, you have an arbitrary shape containing blocks with coordinates in the X and Y axes from 0 to n, where n+1 is the maximum size of a block (traditional Tetris shapes would fit a 4x4 grid). The classic Tetris bar (vertical) would be (1,0), (1,1), (1,2) (1, 3).

To rotate this shape, no matter what the form or size, you simply swap and invert axes.

To rotate clockwise, for every block in the shape, the new block's X would be the previous Y, and the new block's Y would be the inverse of X (n-x). The example rotated bar (now horizontal) would be (0, 2), (1, 2), (2, 2), (3, 2)

To rotate counter-clockwise, the new block's X is the inverse of the old block's Y and the new block's Y is the old block's X.

To put it more clearly:

* Clockwise- x2 = y1 && y2 = n-x1
* Counter - x2 = n-y1 && y2 = x1

This can be done easily in a single method, the two rotations are independent of previous rotations (you could keep rotating clockwise indefinitely and cycle through the same 4 shapes), the code is simple and easy-ish to understand, and it is general enough to apply to any 2D shape composed of blocks. In fact, this is general enough that you could easily rotate even a user-generated shape, let alone any custom shapes you create yourself.

# Answer
> 4 votes
you can concatinate 3 matrices

first a translation to put 1,1 at 0,0, then the rotation and then translate 0,0 back to 1,1

if you use affine transformation matrices this is easy

```
[1,0,-1][0,1,-1][0,0,1] * rotationMatrix * [1,0,1][0,1,1][0,0,1]

```

if you don't use affine transformations then just subtract 1,1 on each point then rotate around 0,0, then re-add 1,1

# Answer
> 2 votes
You are experiencing a 2D version of a common rookie 3D mistake: order of transformation matters. Matrix multiplication is not commutative, i.e. A * B is different from B * A. If you translate the Earth to its correct orbital radius before you rotate it according to the 24 hour clock, you will cause the earth to move along its orbital path (rotating a translation, rather than translating a rotation).

You ostensibly are only performing one rotation transformation. However, your block points were already translated to their position before you began rotating them. @ratchetfreak suggested that you 1. undo the linear translation, 2. apply the rotation, 3. reapply the translation. That certainly would solve your problem, but I would suggest not applying the translation in the first place.

Your T-piece could occupy coordinates relative to its center of rotation (no 0-positions here!)

```
[(-1, -1), (1, -1), (1, 1), (2, -1)]

```

Now if you apply your `R(90)` 2D rotation to these points, they will change to

```
[(1, -1), (1, 1), (-1, 1), (1, 2)]

```

And finally you can add your translation (1, 1),

```
[(2, 1), (2, 2), (1, 2), (2, 3)]
// nobody wants to occupy coordinate (0,0), right?

```

---
Tags: java, 2d, matrix, vector, linear-algebra
---


# Question
Title: Custom Pan/Tilt Input device and Unreal Gaming Engine
I have an augmented reality project I'm doing for a museum, using Unreal Engine. I've begun designing the controller (a pan and tilt visor you look through and move around). Originally, I was designing the input device to emulate a standard mouse output, but because it's augmented reality, will need really good absolute positioning. So I'm looking into absolute encoders for output- it needs to work as soon as you power on with no calibration required.

The question is two parts: if I start building my own input device which outputs discrete coordinates, rather than incremental x and y movement (as a traditional mouse controller chip does) 1) Can I get that data into Unreal Engine? 2) Can I control the camera rotation with that data?

The bigger question is- Is there a better way to do this? All I'm looking to do is build an Unreal Scene with a fixed virtual camera that is controlled by an external Pan/Tilt mechanism.

Many thanks for your input. Ha! Get it. Input.

# Answer
Was searching for the same. Seems you have two options:

1. You can use DLLBind
2. Create native classes

If you have a full license the second approach is preferred according to the description in the link above. But this probably doesn't apply to you because the "full" license seems to include source code access to the Unreal Engine that is intended for full-feature development studios. See Licensing.
> 1 votes

---
Tags: unreal
---


title: as3 game levels : frame to frame

text:
# Question
Title: as3 game levels : frame to frame
which is easy and comfortable when programming a flash game levels. I ask this question for that because if I use frame to frame I will need to write code for each frame code area so the main class file.

Please forget this philosophy and give me a plan for game levels.

thanks in advance :)

# Answer
> 1 votes
You will have only two frames, Main menu with the levels, when you select a level you go to a frame with the game logic, so in the constructor (load method) you read the XML and create your level from it. Something Like

```
<Tiles>
   <ID>1</ID>
   <PATH>/tiles/t1.jpg</PATH>
</Tiles>
<Level>
   <Name> First Level </Name>
   <DataMatrix>
      <data x=0 y=0>1</data>
   </DataMatrix>
</Level>

```

Then what you need to do is to read this data, in the pos 0, 0 you load the tile 1

# Answer
> 1 votes
you can simply store level data in diferent xml or custom format files.

i think this method is the most used one. in that way you are able to dynamicly change or expand levels as you like.

also it's important to know what kind of game you're talking about ?

for example, if youre dealing with tilemap based games, you would store level data like:

1. tiles
2. props and enemys
3. triggers ( like level\_end, or house\_enter )
4. images
5. ...

and so on.

remember that you can store as many data as you need. so for example, you can have multiple layers of tiles, also you can store data for trigger points( like house\_enter or level\_end ) that defines the next level / house.

also keep in mind that you can store all those informations in diferent files, so every level has it's own directory where you can store images, informations and mapdata in sub directorys if you want.

the possibilities are endless.

---
Tags: actionscript-3, levels
---


title: Rotation independent rotation

text:
# Question
Title: Rotation independent rotation
I came up with some cube rotating, but I could not make it smooth and easy to use because as the cube turned - the keys that handle the turning changed their purpose. Link to demo. The demo rotation is done by increasing euler angles and using `Quaternion.Euler()` to get a quaternion for `Quaternion.Slerp()`.

The ideal rotating would be like below: the keys stay the same, no matter how the cube is rotated. A/D turn the cube from "left/right". W/S turn the cube "up/down". Q/E turns the cube's current face.

But I have no idea where to start when making the above. How could the above be achieved?

**EDIT** Rioki's answer solved this question. I was previously using local rotation but changing it to world rotation fixed this. Link to demo.

# Answer
This is somewhat simple. When working with quaternions, to alter the rotation you multiply the current orientation with the change you want to apply. Now there are two ways to to do it:

```
result = orig * change

```

and

```
result = change * orig

```

The nice thing about this is that the one rotates it in the local coordinate system and the other rotates it in the global coordinate system. (As Esa points out, the first rotates around the local coordinate system and the second rotates around the global one.)

I am not sure what you are trying to do, but slerp may be overkill, since it interpolates between two states. The way you describe the problem, is you check what keys are pressed and how much time elapsed since the last tick and then do something like:

```
if (is_pressed('W'))
    orientation = orientation * Quaternion.Euler(dt, 0, 0);
if (is_pressed('S'))
    orientation = orientation * Quaternion.Euler(-dt, 0, 0);
if (is_pressed('A'))
    orientation = orientation * Quaternion.Euler(0, dt, 0);
if (is_pressed('D'))
    orientation = orientation * Quaternion.Euler(0, -dt, 0);

```
> 2 votes

---
Tags: mathematics, unity, rotation
---


title: Creating a simple 3D view of a galaxy

text:
# Question
Title: Creating a simple 3D view of a galaxy
What would be the easiest and most maintainable way to create (or use an already existing technology) a sort of Google Maps in 3D for a galaxy? Its not the main focus of my game, but I would like it to look polished to keep the player immersed.

# Answer
> 1 votes
It depends on how accurate you want it to be. It took scientists years of different camera angles and calculations to get the visible stuff mapped in 3D.

I recommend you take a shortcut. especially if it's not the main focus of your game. Parallax Scrolling (if done correctly) can give you a nifty 3d effect without the 3d. http://en.wikipedia.org/wiki/Parallax\_scrolling

Esentially, you have multiple planes that scroll in each direction, like a background, but at different speeds. The faster you scroll the plane, the closer it is to the camera.

Keep in mind this doesn't work if your camera is able to turn/rotate. You'd have to figure out a different system.

EDIT: Now that I think about it, if you have 3D space, all you really need is to place the planes at different depths in space and when you pan the camera it'll parallax automatically. Still won't work if you turn/rotate the camera though.

---
Tags: 3d, javascript, maps
---


title: Fruit Ninja Swipe

text:
# Question
Title: Fruit Ninja Swipe
I now have nearly completed a Cut The Rope type game. I need only a swipe mechanic to cut the rope, both the logic and the visual effect. Suggestions would be most welcome.

I only need a concept for what to do in this situation. I tried doing it in two ways already, but I don't satisfied with it.

1. I used a particle system, but I get random points on the screen. So the effect does not convey its meaning. I have following link in which I have implemented a line drawing algorithm with particle system. https://stackoverflow.com/questions/10702328/drawing-line-effect-on-touch-like-fruit-ninja-or-veggie-samurai-in-and-engine
2. I used a simple and single sprite, and perform scale, transformation, and rotation but I don't get desire effect that looks perfect for rope cutting.

I have knowledge about CCBlade class in cocos2d but I found it difficult to convert it into Java.

Any help is greatly appreciated.

# Answer
> 3 votes
Here in the following link I post my code that I used to create ninja swipe effect.

http://www.andengine.org/forums/gles1/draw-gl10-gl-triangle-strip-fruit-ninja-swipe-effect-t7257.html

This link contains whole discussion about this topic but at last I post my code and image so any user can immediately create this effect.

# Answer
> 2 votes
For the cutting-line drawing, I could think of a simple logic that tracks user input with a short interval and draws lines from the tracked points like this -\>

If the user is cutting ( touching the screen / mouse down + move ) you could check the cursor position point in a desired interval, and draw a line from the last point to the current point until user stops cutting ( mouse up ).

While cutting ( mouse move ), vou could apply a simple particle system where the emitter is following the input position. play with some values in the particle system to make sure that the spawning point is just in place, by applying a force ( gravity ) you can make the particles fall down. Play with the lifetime value.

To animate the "rope" that is been cut, you could define a "force" value to the rope. By detecting if the rope and the cutting-line are overlapping, you can define the cutting point, where the animation starts, the upper end of the rope is just pushed up a little bit ( defined by the force of the rope ) and the lower end is just falling down.

I think you'll find some good techniques on "chain animation" or something. This would be a little bit of work to the physics engine.

Well, this is just my theory. I have never done this kind of game before.

I hope this idea helps you find your solution.

# Answer
> 2 votes
I might do it this way... I wrote a game that had a throwing mechanic using the mouse, and its similar. I'm also assuming you are using touch primarily.

Get the time when your finger touches the screen. On the touch move callback, see how much time has passed and how far you have gone from the original point. You can get the distance using Pythagoreaus' theorem (sqrt(x^2 + y^2)). Set a threshold for the swipe to trigger. If the distance traveled / time taken \>= threshold, trigger the swipe functionality. It's a basic software accelerometer, but should be effective.

I might also have a stop time condition because you don't want your slash to go on forever.

---
Tags: game-mechanics, andengine
---


# Question
Title: Government or NGO grants for game development
I live in the United States, and I was curious whether or not any governmental grants or NGOs (Non-Governmental Organizations) support game developers via grants or other funding options for games that are not directly developed for commercial gain.

After a quick googling, the only examples I could find were the NEA media arts grant which is restricted to games that can be claimed to be art (arguably all of them), and the ESA Foundation which focus on games for learning but are restricted to giving funding to non-profit organizations.

Are there any other institutions that accept applications for games from individuals? Perhaps similar to Y-Combinator where you have to present a short video of yourself, and a working prototype of your game along with background of the team you will be using to develop it? I'd also like to know whether or not there are institutions that would like to promote a certain cause or aspect through game development by providing developers with resources to pursue this? (Similar to this DOE project)

# Answer
> Kickstarter.com

Or other fund raising platforms that give you the ability to gain money from a large range of future customers. You sell the product, before it is made. Read the Kickstarter.com FAQ for the way it should be used.

It is not actually a grant, but suits your needs. Because you are given a "Grant" by the community, if you get enough people to sponsor you. It is either, all or nothing. If you set a goal of $1,000,000 and you after a chosen period of time. you wont reach your goal you will not get any money. If you exceed your goal you will get the money -5% Kickstarter payment.

> You are not allowed to give anybody company shares in exchange for funding the kickstarter.com funding.

.

> You can make all types of games. And get money for creation of your game, before you have any type of prototype/demo.

A recent project, Torment: Tides of Numenera, has beaten the fund record gaining over 4 milion dollars for their product development.

http://www.kickstarter.com/discover/categories/games/most-funded?ref=more#p1
> 2 votes

---
Tags: fund-raising, serious-games
---


# Question
Title: Help me please to choose proper path-finding algorithm
I am new to game development and just want to ask for advice. I need to know which path-finding algoritm will be suitable for my scenario:

1. Units - any shape. But in most cases rectangles of different sizes.
2. I have random generated maze and destination point or area.
3. Because of different maze borders not all unit can fit and move to the end.

How to find path from unit to destination area and check that shape can move to this area?

# Answer
A\* is the logical choice. Your main concern is going to be with generating good navigation nodes. The nodes will tell you everything you need to know about how traversable each node is with respect to each unit.

Having size information associated with your nodes will be very helpful to you. In the above, we see a size 1 unit can use any of the nodes.

Where the same map for a size two unit looks pretty different, since all the size 1 areas are also non-traversable:

The above images are from the article "Clearance-based Pathfinding and Hierarchical Annotated A\* Search". There are additional implementation details to be found there.

You don't have to implement a fixed grid to keep size information, you can also create nodes that have a 'best fit' approach and fit the largest area possible:
> 12 votes

---
Tags: algorithm, path-finding, collision-resolution, collision-avoidance
---


# Question
Title: What does this error mean? (Reach profile?)
I got this, when I tried to load a model during runtime

> XNA Framework Reach profile requires mipmapped Texture2D sizes to be powers of two, but this Texture2D is 800x800. Resize it to a power of two, or remove the mipmaps.

What does it mean? What do I have to do?

# Answer
> XNA Framework Reach profile

You are using the XNA Reach profile. This is a profile designed to make your game run on as many computers as possible. It is a pared-down subset of XNA's full functionality. The alternative is the HiDef profile, which exposes all of XNA's functionality, but has stricter hardware requirements.

> requires mipmapped Texture2D sizes to be powers of two

One of the requirements imposed by the Reach profile is that textures with mipmaps have to have dimensions that are powers of two.

> but this Texture2D is 800x800.

Your model is using a texture. The texture is 800x800 and has mipmaps (as is usually the case). 800 is not a power of two. The closest acceptable size would be 1024 (2 to the 10th power).

> Resize it to a power of two, or remove the mipmaps.

Do one of these two things.
> 10 votes

---
Tags: xna
---


# Question
Title: Spatial data visualization level of detail
I have a 3D point cloud data set with different attributes that I visualize as points so far, and I want to have LOD based on distance from the set. I want to be able to have a generalized view from far away with fewer and larger points, and as I zoom in I want a more points correctly spaced out appearing automatically.

Kind of like this video below, behavior wise: http://vimeo.com/61148577

I thought one solution would be to use an adaptive octree, but I'm not sure if that is a good solution. I've been looking into hierarchical clustering with seamless transitions, but I'm not sure which solution I should go with that fits my goal.

Any ideas, tips on where to start? Or some specific method?

Thanks

# Answer
i would consider looking into GIS based methods firstly although i do not know exactly how this would relate within a game.

https://gis.stackexchange.com/

if i were to write from scratch for simplicity purposes however, i would scale the 2d positional Vector and group the value by those scaling within a given range i.e if you had a 1000 pixel map condensed into a 100 pixel area you could simply sum the values based upon the Vector2D /10 and provide a single pixel value color based upon this. obviously you could extrapolate this for 3d.

Would probably work very well as a shader but my knowledge does not stretch anywhere near that far

(not sure if this goes anyway near to answering)
> 1 votes

---
Tags: level-of-detail, visualization, point-cloud
---


title: Making a sun out of a light

text:
# Question
Title: Making a sun out of a light
Basic stuff, I guess. Can I somehow make a sun out of a light-source in XNA? I would like to be able to see the light, actually, and set it on the upper right corner like a sun.

# Answer
> 3 votes
It's possible to use a point light source for the sun, whether you are wanting to simulate what the sun looks like if you look at it, or the just light it shines.

TLDR; yes, but make it as far as you can away from the player and don't have any light falloff.

Essentially you can think of the sun as being a point light source that is infinitely far away. No the real sun isn't a point nor is it infinitely far away, but it's "close enough" you can think of it that way. The problem is, how do you make a point light source that is "infinitely far away"?

If the point light is too close, then shadows will not all be cast parallel. Image you had a fence with a gap between every board, and the sun was setting behind it. Every beam of light coming through (or board shadow) would be parallel. But if you had a closer point source, the shadows would spread out in a sort of fan, leading back to the point source.

Also if the point light is too close, and it is visible via some kind of lens flare or halo glow, the player will notice their position is different relative to it as they move. Imagine if the real sun were frozen in the sky on the western horizon for a moment. If you start walking south, it's going to basically stay in the same place in the sky unless you walk a very long distance. But if the sun (or your point light) were close up, then you would see it change position in the sky as you walked farther south.

Lastly, for all intents and purposes, the light from the sun doesn't fall off (get dimmer at a distance). Yes it does if you move millions of miles away from it, but if you go hundreds (or thousands) of miles nearer or farther away, it basically stays the same brightness as far as your eye can tell. So you need to make your point light source do the same - not have a falloff where it gets dimmer as you get farther away.

---
Tags: xna
---


title: Bounding Boxes and XNA

text:
# Question
Title: Bounding Boxes and XNA
So heres some straight up code for you:

```
BoundingBox b  = new BoundingBox(
  Vector3.Up   + Vector3.Right    + Vector3.Forward,
  Vector3.Down + Vector3.Backward + Vector3.Left);
BoundingBox bb = new BoundingBox(
  Vector3.Up/2   + Vector3.Right/2    + Vector3.Forward/2,
  Vector3.Down/2 + Vector3.Backward/2 + Vector3.Left/2);

Debug.GraphicsManager.DrawLine(b, Color.Purple);
Debug.GraphicsManager.DrawLine(bb, Color.Yellow);

if (bb.Contains(b) == ContainmentType.Disjoint)
  Debug.DisplayVariable("Disjoint", "");
if (bb.Contains(b) == ContainmentType.Contains)
  Debug.DisplayVariable("Contains", "");
if (bb.Contains(b) == ContainmentType.Intersects)
  Debug.DisplayVariable("Intersects", "");

```

What this does is create two bounding boxes, that /obviously/ intersect. DrawLine is a function that accepts a bounding box and draws it. Math and visuals tells us that these intersect and contain.

But all I get is disjoint.

So I started a new blank fresh clean project and only added this to the update code:

```
BoundingBox b = new BoundingBox(
  Vector3.Up + Vector3.Right + Vector3.Forward,
  Vector3.Backward + Vector3.Left);
BoundingBox bb = new BoundingBox(
  Vector3.Up / 2 + Vector3.Right / 2 + Vector3.Forward / 2,
  Vector3.Backward / 2 + Vector3.Left / 2);

if (bb.Contains(b) == ContainmentType.Disjoint)
  System.Console.WriteLine("Disjoint");
if (bb.Contains(b) == ContainmentType.Contains)
  System.Console.WriteLine("Contains");
if (bb.Contains(b) == ContainmentType.Intersects)
  System.Console.WriteLine("Intersects");

if (bb.Intersects(b))
  System.Console.WriteLine("intersex");

```

and this has the same problem.

So I'm stumped. Does XNA just not have good bounding box collison code? Or am I doing something wrong? should I write my own collison code?

Thanks for reading, no this is not debug for me, I simply don't understand.

edit: I also have mouse picking set up and it can identify and pick all my "models" based on Ray.Intersects(model.boundingbox) no problem.

# Answer
> 1 votes
The problem is is the order of your constructors. This works correctly. I put all the negative static `Vector3` values into the min, and the positives into the max.

```
BoundingBox b = new BoundingBox(
  Vector3.Left + Vector3.Forward,
  Vector3.Backward + Vector3.Up + Vector3.Right);
BoundingBox bb = new BoundingBox(
  Vector3.Left / 2 + Vector3.Forward / 2,
  Vector3.Backward / 2 + Vector3.Up / 2 + Vector3.Right / 2);

```

---
Tags: xna, collision-detection, bounding-boxes
---


# Question
Title: How would one create a "start button" on a website similar to some Korean games?
Some games have buttons that would actually let you click them and you'd log right into the game. How does the web browser get permission to do this without plugins? Perhaps the client registers a custom protocol URL?

They used to be popular a few years back - I can't remember any implementations off the top of my head. On desktop browsers, if your game client was installed clicking 'Play' on the home page would boot up the game begin it with you already signed in. It was popular with arcade games so you could browse the sessions on the web and then simply hit 'Start'. You didn't need any browser plugins.

# Answer
I have not seen any games that do this, but I can think of a few ways to achieve this. Keep in mind that any solution will be browser and OS dependent, so you must offer alternative ways to start your game.

In general, my approach would consist of running your game's executable file from the browser. Here are some ideas I just made out. I'm not really sure whether or not they work for your purposes, or if they even work at all, but they may give you some ideas.

1. `WScript.Shell`. Only works on IE, but is probably your most flexible choice.
2. The `mozilla.org/process` XPCOM component would do the same thing in Firefox.
3. Execute the program from a signed Java applet. I haven't done applets in ages, but last time I checked, you could access local data XOR the internet from an applet, if it is properly signed.
4. Execute the program from a flash applet. This would be very similar to the Java applet.
5. Have the browser download a file with a custom extension, which your game previously registered. This requires a confirmation dialog, but is probably the most portable.
6. Have the link point to a custom URL scheme/activity which was previously registered by your game. This only works on iOS/Android, and is the mobile analog of the previous point.
7. Use a plugin. Most likely your game installer requires admin privileges, so use these privileges to install plugins for the currently found browser(s).
8. Make the button into a link to the locally installed game executable (via `file://`). This will fail when the game is not installed though.

But, if you can find a working example, you can check the page source, and at least get a hint of how they're doing it.
> 2 votes

---
Tags: javascript
---


# Question
Title: Weapon as camera's child, rotation messed up
I put my weapon as a camera child, it works, but when i rotate my player it seems the weapon rotate a little too.

I'll attach some images so you can see it.

As you can see, when i look up i can see a little bit more of the weapon and when look down to. I'm using the default 1st person script. Am i missing some important point here?

Regards, Alex.

# Answer
Usually assign a child to camera is a bad idea. It will work, of course, but can give a little headache in your hierarchy. Try to create a new empty gameobject and assign camera and the weapon to it (even if i dont like that main camera is a child).

For your problem, i simply cant get it and your images are not clear (i didn't see anything wrong, remember that u are in First person and the prospective). If an object is a child of another one, the child object will just follow the rotation/transform update of the parent.

P.s. Try to write your own character controller, even if people say that you can use Unity without knowing programming... well, it's a lie :)

If you need more help, please explain better your problem.
> 1 votes

---
Tags: unity, camera, rotation
---


# Question
Title: Deploying GWT application / LibGDX and TextureAtlas problem
I encountered with a little problem. After GWT (and LibGDX) deployment I got an error:

> GwtApplication: exception: Couldn't load image '/images/objects.png', file does not exist Couldn't load image '/images/objects.png', file does not exist

This error throws when TextureAtlas tries to load the image from *settings.text* file:

> images/objects.png
> format: RGBA8888
> filter: Nearest,Nearest
> repeat: none
> hills
> rotate: false
> xy: 0, 0
> size: 1024, 146
> orig: 1024, 146
> offset: 0, 0
> index: -1

I tried to use any type of path

* "**/assets/images/object.png**"
* "**/clutchkick/assets/images/object.png**"
* "**/public\_html/clutchkick/assets/images/object.png**"
* and so on..

Any suggestions?

By the way there are no any problems on android or desktop deployment.

EDIT: The same problem occurs when trying to load a Tmx map.

# Answer
There's a bug in **com.badlogic.gdx.backends.gwt.GwtFileHandle** that adds a slash before the image path in the atlas, but here is a workaround:

Put the *atlas* files are inside a folder like **"assets/images/"**, don't put it directly in the assets folder, and make sure the *image path* in *atlas* file is correct (relative to atlas), then it should work.

---

Or you can just fix the **GwtFileHandle** class:

Find this code in **com.badlogic.gdx.backends.gwt.GwtFileHandle**

```
public FileHandle child (String name) {
    return new GwtFileHandle(preloader, file + (file.endsWith("/") ? "" : "/") + name, FileType.Internal);
}

```

And change it to following code

```
public FileHandle child (String name) {
    return new GwtFileHandle(preloader, file.isEmpty() ? "" : (file + (file.endsWith("/") ? "" : "/")) + name, FileType.Internal);
}

```
> 5 votes

---
Tags: libgdx, texture-atlas
---


title: front and back face detection

text:
# Question
Title: front and back face detection
I am trying to implement a dynamic shadow system for a 2d game using this tutorial :

http://www.gamedev.net/page/reference/index.html/\_/technical/graphics-programming-and-theory/dynamic-2d-soft-shadows-r2032

but I am stuck at the point where I need to determine which face is front facing or back facing the light source.

Is there a simple technique to apply in order to find out which face is in front and which one is in back?

# Answer
The dot product of the each face's normal with the vector from the face to the light position should distinguish which faces are front/back.
> 2 votes

---
Tags: vector, shadows, lighting
---


# Question
Title: A* path finding for road network - data structure to represent directivity
I have been reading A\* path finding to apply on a road like network structure. Most of the code I saw is about A\* on tile based maps. There is a short description at Amit's page here about what I am looking for. My question is about what data-structure should I use to define a road network map.

I have infromation like, node, cost,etc. But not sure how to represent both one directional and bidirectional roads. In a graph structure, can I mix directed and undirected edges or use two edges to represent that a segment of road can be traversed in both direction. Any good example available?

Thank you so much.

# Answer
> 6 votes
The edges of a graph are implicit; they are defined by each node's adjacency list.

If node A has both node B and C registered as adjacent nodes, but only node B has A registered as an adjacent node, then the edge between nodes A and C is implicitly directed towards C.

Nodes can be implemented as a collection of its adjacent nodes and its data (position would be relevant to pathfinding).

```
struct Node
{
    std::set<Node *> adjacent;

    Vector3 position;
};

```

# Answer
> 1 votes
In road network it is better to have cost in edges, not in nodes. When I was doing road networks (for navigation, not for games) related programming, I used Node that contained set of incoming and outgoing edges (and other data) and edge with both ends, reference to edge in oposite direction and again, other data.

Some of this you will probubly not need (depends on what you want to do with this graph. For A\* I would guess that you need: cost of edge, cost to reach node from start, outgoing edges and used incoming edges (for creating actual path once you find cost of path to goal).

Another complicating thing (that can significantly reduce size of graph): Nodes with 2 neighbours are not interesting, unless they are start or goal, theefore you can create simplified graph where they are romeved and replaced with edges connecting their neighbours (if they were originaly connected by removed node)

Nodes with just one neighbours are not interesting too, so they again can be removed.

Applying both these rules can in some cases reduce graph size multiple times (on some islands it reduced our graph to single node which was not so usefull ;) ), but in grid like road network it will help only little.

How excatly I represented this I don't remember (proprietary work I did few years ago).

And my experience was not with games, but with preprocessing graphs, so I had lot of memeory available (eg. Vieana needed computer with more than 4GB ram)

---
Tags: path-finding, maps, navmesh
---


title: Keeping raycast on the same level

text:
# Question
Title: Keeping raycast on the same level
I want my raycast to end at certain height(red line). But as the game is 3D and the camera rotates I can't use a fixed magnitude. What I thought was a stroke of genius, I figured I'd project the height vector(a) to the ray direction to get vector(b). The result is in the right direction, but the magnitude of b is not big enough.

The wanted result is to get the vector b always reach the red line(Magnitude changes depending on the camera). My previous knowledge of vector projection says it should work, but obviously it doesn't. Where am I going wrong here?

**---- EDIT: Question clarification ----**

Step one: The ray is cast depending on used input. And it fails to hit any of the gameobjects.

Step two: Check the area around the midlevel(redline) to see if any gameobjects are close enough(green circle). For this to work, I need the magnitude of b-vector to use the `Ray.GetPoint()`.

# Answer
> 1 votes
You know the length going from the red line to the top of the blue line, right? Then you can apply some basic trigonometry.

The blue line and the red line are the legs of a right triangle. Your desired line from the camera to the red line in the direction of the raycast is the triangle's hypotenuse (origin at the camera):

Given an angle, `theta` between the hypotenuse and some leg of a right triangle:

```
cos(theta) = adjacent_leg_length / hypotenuse_length

```

But you don't have the `hypotenuse_length`, so you'll rearrange it like so:

```
hypotenuse_length = adjacent_leg_length / cos(theta)

```

Assuming you have your `raycastDirection`, `cameraPosition,` and `redLineHeight` as demonstrated in your screenshots, here's how to get a relative vector representing this hypotenuse:

```
Vector3 cameraPosition = GetCameraPosition();
float redLineHeight = GetRedLineHeight();
float cameraHeightFromRedLine = cameraPosition.y - redLineHeight;
float angle = Vector3.Angle(Vector3.down, raycastDirection);
float magnitude = cameraHeightFromRedLine / Mathf.Cos(angle);
Vector3 yourNewVector = raycastDirection.normalized * magnitude;

```

Now that you have this new vector, you can do a check at the end of it with `Physics.OverlapSphere`:

```
float checkRadius = GetCheckRadius();
Collider[] hits = Physics.OverlapSphere(cameraPosition + yourNewVector, checkRadius);
foreach (Collider hit in hits) ProcessHit(hit);

```

Alternatively, if you have a list of hittable GameObjects and there aren't that many in that list, you can bypass the `Physic.OverlapSphere` call and do a squared distance comparison on each. The advantage of using Physics.OverlapSphere is that PhysX does smart things to prune colliders it would otherwise have to check against. But if you already have that list filtered down enough, you can save on not having to call out to the native physics code. It all depends on the cost of iterating through your hittable set vs the cost of calling out to Physics.OverlapSphere. Start with OverlapSphere for simplicity, and then if you find yourself needing to cut down on physics calls, then this is one place to possibly look at after you profile.

If you need to bone up on trig, Khan Academy has some videos.

# Answer
> 1 votes
You can use Physics.SphereCast instead of RayCast. This allow you to perform queries of the intersection of a sphere sweeped along a given direction instead of single ray, allowing a more tolerant collision detection.

Assign at least two different layers to the plane and the `GameObjects` under it, in order to exclude the plane from the query.

# Answer
> 0 votes
Instead of using Linecast, which, if I understand correctly, you use now, I'd suggest Raycast function, where the length of the direction vector doesn't matter. (By the mathematical definition, ray doesn't have an end.) If you want to be able to select a specific type of objects, it usually makes sense to assign these objects to a specific layer in unity and use layerMask. I think that this approach is better for your task, because this way the filtering of selected objects isn't tied to some specific knowledge about the position of camera or the objects; it is tied to the layer the objects are in, and it makes much more sense.

---
Tags: mathematics, unity, vector, projection, raycasting
---


# Question
Title: Getting BEPUphysics to draw its entities
Isn't there a way, to force BEPUphsyics to show what it is doing? I am here with my existing XNA project, starting to put in BEPUphysics, but I am not seeing what it is doing.

Take my model for instance. I think I made a `StaticMesh` here:

```
public BEPUphysics.Collidables.StaticMesh PhysicsMesh;
public Space space;
private Hero _hero;

public override void LoadContent()
{
   //...

   space = new Space();
   Vector3[] vertices;
   int[] indices;
   TriangleMesh.GetVerticesAndIndicesFromModel(_model.getCoreModel(), out vertices, out indices);
   PhysicsMesh = new BEPUphysics.Collidables.StaticMesh(vertices, indices, new AffineTransform(new Vector3(0, -40, 0)));

   space.Add(_hero.PhysicsMesh);
   space.ForceUpdater.Gravity = new Vector3(0, -9.81f, 0);
}

```

That's the only thing I made BEPU-Wise in my game. All other models don't have physics attached to them.

But, like I said. I see nothing when the game is running. Only my model, not falling, not doing anything.

I would like to see the full thing BEPU is doing in runtime.

# Answer
> 1 votes
Drawing bounding boxes is a good solution, I have found. When I integrated BEPU into my engine I added code to do two things:

1. Draw the bounding box of the model in a certain color.
2. Draw the bounding box of the physics objects in another color.

This really helped me to find all the various issues between the two\*, and makes the positions quite clear. You'll have to do a bit to construct a bounding box from the static mesh, but it isn't too bad.

* Importantly, the origin point of the static mesh made from your model will likely not be the same as the origin of the model. Rather it will be the 'center' of the object, vs the origin assigned in the modeling program. You'll likely need to figure out the offset between the two and draw the model with the offset so it is at the proper position per the physics object.

---
Tags: xna, physics
---


# Question
Title: What type of legal entity do I need for my game company in the USA?
I'm the leader of a group of 4 of us that are contributing to a game and it has come to my attention that we will eventually need some kind of official title or something along those lines. We've agreed on a name, and we've already got a domain name and several back-end resources that I've set up under the brand as well.

I'm curious as to the steps needed to be taken to make it "official" and protect my assets. Is this something I'm best off worrying about closer to release?

I've looked at this post, and I was also taking a look at this page. However, I want some straight answers from people who may have been down similar roads in the past.

# Answer
> 5 votes
This is something you probably want to talk to lawyer about. That sounds like it will cost money, but it will probably not be as much as you think and many lawyers can give you a consultation up-front (at no or a minimum fee) to give you a better idea of what the net cost to you would be. Additionally, it costs money to make money, and you're almost certainly better off spending the money up-front on a lawyer than spending the money later on when things get pear-shaped and you're not properly covered.

For context, the three of us who worked on SlimDX, an open-source "spare time" kind of project, formed a legal entity to act as the container for all the work.

You probably have a few reasonable options (all of these are US-specific, which should be fine as that appears to be where you are located):

* Sole proprietorship
* Partnership
* Limited liability company (LLC)

There are additional business structures available in the US (such as S and C corporations), but they are *probably* too heavyweight for your needs. The IRS has a nice page breaking down all the business entities and what the implications are for ownership, taxes, et cetera. I feel like I see a lot of indie developers form LLCs, but that's purely my own opinion and should not be considered legal advice.

You should settle the issue of business organization and legal issues surrounding ownership of the intellectual and physical property as soon as possible, ideally before you develop anything significant. You want to be able to answer questions such as "who owns what if this whole things collapses, what if one of the members leaves, how is our profit split up?" and more, and the sooner you do that the less complicated things will be later. Talk to a lawyer.

A lawyer friend of mine wrote this article on "The Business and Legal Issues Surrounding Game Development Team-Building" and also this chapter concerning legal challenges in a book. I'd recommend reading them.

Here's another article on a "legal crash course for indie developers" you may want to check out. Note that I can't vouch for this author in any way, I just stumbled across it while researching for this answer.

# Answer
> 4 votes
Great questions! Here's my two cents.

**Starting the Company**
Seeing that you've already secured a domain name and necessary assets, I would suggest starting the process of creating your company. Depending on your state, it could take a few months for the paper work to finalize. Different states have different forms, regulations, fees etc. I find the easiest process is to hire a legal service to handle everything for you. It ups the costs a little but avoids all the hassle. For instance, many states require an official Operating Agreement form. Also, the legal service can act as your Registered Agent then. I believe that's a must for most states.

There are many online legal services to pick from. I suggest one of following:
InCorp Services
LegalZoom

**What Kind of Company**
There are certainly a lot of choices here but for sure you want to start an LLC. It's great for tiny start ups and handling taxes is a breeze...relatively speaking. As an LLC your team can all be considered "members" of the company. You can think of members as part owners. If you want to be the sole owner/member, that's fine but then you'll need to start worrying about paying employee wages which adds further complexity.

Further Reading:
Company Type Differences

**Handling Taxes**
The big benefit of an LLC comes with taxes. All company profits are distributed directly to it's members. This is called pass thru taxation. That means the company itself doesn't pay any taxes, only it's members. Members still file a standard 1040 tax form but ensure to claim the income received from the LLC.

The only difference then comes with paying quarterly estimated taxes. This is standard for any company, sole proprietary, or even for independent contractors. Basically, 4 times a year you must pay taxes on your estimated profits for that year. Then when you do your final "normal" taxes you determine if you over/under payed. Trust me, you want to over pay. Here's a great link that talks you through estimated payments: Estimated Taxes. Remember, that's only for the feds. You have to do this also for state and local.

Estimated taxes brings one important lesson to the table. Setting aside a chunk of your revenue for taxes. If your game pulls in $1000 dollars in one month, you NEED to set aside a percentage of that to give to the government. Personally, I have to set aside 40%! And no I'm not even making close to 6 figures.

**Tracking Income/Taxes**
I'm sure there are great resources for doing this, however I do all my estimated payments by hand. Trust me, it's far easier then doing normal income taxes. When you are tiny, this is trivial. Larger companies will be different. Hiring a tax service is a viable option but (in this case) the hassle is not worth the cost.

Since I'm only one person, there isn't much to track. I'd imagine the same would be for you and your team so I would just use a simple spreadsheet. Any purchase or expense for the LLC is recorded there and later used to determine your actual profits. Of course, you can just get a company credit card and always use that to track expenses instead. Just make sure the CC company maintains a billing history for over a year.

Otherwise you can use whatever tax service for handling the end of the year taxes. Such as H&R Block or TurboTax.

**Final Thoughts**
This probably sounds very overwhelming. Especially when it comes to taxes. It'll probably be rough in the beginning. The initial learning curve is somewhat high but once you get a handle on things, it's not too bad and becomes second nature eventually. When I went through all this, the most significant thing I learned was just how much the government taxes add up. As an employee, you don't see all the additional taxes a business must pay on your behalf.

---
Tags: business
---


# Question
Title: onTouchEvent only working for one view within activity
I have a parent Activity which contains 2 views. One view is a custom view class, where I am overriding the onDraw method. This view contains an onTouchEvent function, which is checking for user clicks within the view.

Below this view I have another view, which is a view extending LinearLayout, which contains 9 buttons which are numbers to be selected by the user\[I am basically trying to build a simple Sudoku game\]. Now user clicks on my top view, which is the Sudoku Grid works fine, but it is calling the onTouchEvent of the top view, even when I click on the buttons within the bottom view keypad.

I have tried everything, from setFocusable(true), in the XML, in the constructor, from the parent activity. I even placed a onTouchListener on the keypad view. This listener is getting called when I click anywhere within the keypad view, except for on the buttons???

How can I detect a keyPress on the bottom view??

The bits of code

```
public class TrialBoard extends View{
@Override
public boolean onTouchEvent(MotionEvent event){
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
 selX = (int)event.getX();
 selY = (int)event.getY();
 Log.d(TTAG,"Touch X : " + selX + " Touch Y : " + selY);
 getRect(selX, selY);
 return true;
}else
if((event.getAction() == MotionEvent.ACTION_CANCEL)||(event.getAction()==MotionEvent.ACTION_OUTSIDE)){
 return false;//TRIED THIS BUT NOT WORKING
}else{
 return super.onTouchEvent(event);
}

```

}

```
public class CustomKeypad extends LinearLayout {

@Override
public boolean onTouchEvent(MotionEvent event){
    if(event.getAction() == MotionEvent.ACTION_DOWN)
    {
        Log.d(KTAG,"Inside onTouch of keypad");
        return true;
    }else{
        return super.onTouchEvent(event);
    }
//NOT GETTING CALLED AT ALL
}
}

public class TrialActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    Log.d(TRIALTAG,"Inside on create");
    setContentView(R.layout.trial_activity);
    keypadView = findViewById(R.id.keypad);
    selNumber = 0;
    keypadView.bringToFront();
    keypadView.setFocusable(true);
    keypadView.setFocusableInTouchMode(true);
    keypadView.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event){
            Log.d(TRIALTAG,"Inside keypad view touched listener event");
            return true;
        }
    });
}
}

```

EDIT 2: My XML for keypad:

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="@drawable/keypad_background" >

```

```
<TableRow >
   <Button android:id="@+id/keypad_1"
       android:text="@string/key1"
       android:padding="2dp"
       android:onClick="num1Clicked"/>
   <Button android:id="@+id/keypad_2"
       android:text="@string/key2"
       android:padding="2dp"
        android:onClick="num2Clicked"/>
   <Button android:id="@+id/keypad_3"
       android:text="@string/key3"
       android:padding="2dp"
        android:onClick="num3Clicked"/>
</TableRow>
<TableRow >
    <Button android:id="@+id/keypad_4"
        android:text="@string/key4"
        android:padding="2dp"
         android:onClick="num4Clicked" />
    <Button android:id="@+id/keypad_5"
        android:text="@string/key5"
        android:padding="2dp"
         android:onClick="num5Clicked" />
    <Button android:id="@+id/keypad_6"
        android:text="@string/key6"
        android:padding="2dp"
         android:onClick="num6Clicked" />
</TableRow>
<TableRow >
    <Button android:id="@+id/keypad_7"
        android:text="@string/key7"
        android:padding="2dp"
         android:onClick="num7Clicked" />
    <Button android:id="@+id/keypad_8"
        android:text="@string/key8"
        android:padding="2dp"
         android:onClick="num8Clicked" />
    <Button android:id="@+id/keypad_9"
        android:text="@string/key9"
        android:padding="2dp"
         android:onClick="num9Clicked" />
</TableRow>
</TableLayout>

```

I added the onClick later, coz I realized too late that this was a easier and saner way to get a button click event. I guess in a way I do deserve a flag down coz I should have remembered this, but I am still puzzled as to why it would not pick up the button click on the onTouchEvent.

# Answer
> 2 votes
It does not work because the buttons are Views too, just as LinearLayout and since they are on top they need their own "onTouchEvent" listener, which is onClick listener in their case. LinearLayout does not detect the touch on its children views because the children overtake the touch events for themselves.

But did you try to touch around the button? Then the LinearLayout's onTouchEvent may work.

# Answer
> 1 votes
I believe the problem is that your custom view is somehow overlapping the linearlayout. An easy test is to add the following into your **Drawable** resource folder.

**border.xml**:

```
<solid android:color="@android:color/background_light" />

<stroke
    android:width="1dp"
    android:color="@android:color/black" />
</shape>

```

Then for your custom view, set it's background image to the **border.xml** resource. That background will draw a black outline around the perimeter of your View. You should also comment out the onDraw() method for this test.

---
Tags: android, view
---


# Question
Title: Flip the whole Directx output horizontally (mirror the output)
I would like to flip the whole fullscreen directX output horizontally so that the final output is presented mirror inverted.

Is there a way to create a `IDirect3DDevice9` instance which produces mirrored output? Or even better: is there a way I can mirror the output just before the final call to the `Present(...)` method of the `IDirect3DDevice9`?

**Update/Clarification:** The underlying objective is to be able to use a projector which needs vertically flipped input. The software I am currently using allows to register callbacks and hands over a handle to the `IDirect3DDevice9` instance. After my method is called and returns, the directx output is presented. This repeats after each frame.

I would like to flip the presented output horizontally.

I tried the following:

* Use settings of the projector to flip the image (not supported)
* Find a setting in the Operating System (windows7 doesn't support flipping of the image)
* Find a setting in the graphics driver (AMD Catalyst) but only rotation is supported, not horizontal flipping

I have only little experience with directx so please bear with me (this is also why I would appreciate sample code or at least pointers to the right direction).

**Update2:** I found out that I should be able to call `SetTransform` on the `Direct3DDevice9` handle to change the `D3DTS_PROJECTION` with a proper Matrix. However this does not work in my example application.

# Answer
You could either adjust your projection matrix appropriately, or else do a render-to-texture and draw that texture as a fullscreen quad with flipped l and r values in an off-center ortho projection. Depends really on what you're trying to achieve with this, i.e. what's your underlying objective here? Is this for a mirrored view? Etc?
> 4 votes

---
Tags: c++, directx9
---


# Question
Title: How do indie game developers make money?
How exactly do they make money their money? Do they go by a paid-per-copy system, or some other form of compensation?

Edit: To clarify, I just saw "Indie Game - The Movie" and was wondering how developers like Team Meat get compensated for every copy of the game they sell. Do they get say, a dollar for every $10 copy?

# Answer
> 6 votes
* **Sales**: Selling their game, per copy. Or selling the rights to their game.
* **Ads**: Advertisements placed in game, on their website, etc. Admob, Adsense, etc.
* **In-App purchases**: Mainly mobile apps, in app purchases can be character upgrades, xp bonuses, etc.
* **Dontations**: Releasing their game for free, and asking for donations. Dwarf fortress does this.
* **Subscriptions**: Recurring fees to play their game, typically in an online setting.
* **Their day job**: Many indie developers don't make money from their games. They have to work a *real* job to get paid.

# Answer
> 0 votes
This question is too broad and basic, but there are a number of ways monotize your game (see but does ROTMG make $$$? section).

1) Sell it on your website / via Steam or in an appstore like the Apple App Store or Google Play

2) In-app purchases (managed by Apple App or Google Play)

The world of in-app purchases is huge. And what you can sell depends on what kind of game it is .. is it a persistant MMO type world? Then have permadeath and sell scrolls of resurrection in the store. Is it a shooter? Then sell the ability to "unlock" the better weapons. The list goes on, what you can sell as in-app really depends on what your game about.

---
Tags: game-industry
---


title: Java Tetris - Matrix Rotations

text:
# Question
Title: Java Tetris - Matrix Rotations
I'm building Tetris in Java and am trying to use linear algebra to rotate a piece composed of 4 tiles.

My friend was explaining the way to do it is:

**He said:**

> "To clarify, you do need to rotate each point -- that is you need to rotate one point for each Tile in a Piece. But NOT four corners for each Tile in a Piece. The origin is like if you stuck a pencil through a piece of paper and spun the pencil around.. the spot where the pencil is is the origin."
>
> "So if you have a T on your board with Tiles at (7,9) (8,9) (9,9), (8,10) and its origin is at (8,9).."

So I'm doing it with coordinates (1, 3) (1, 2) (1, 1) (2, 2)… with origin (1, 2)

**Then he said:**

> "You translate the Tiles to be relative to the origin. That is, you treat the origin as the new (0, 0) for this rotation. That's as easy as just subtracting the origin from each coordinate, giving you (7-8, 9-9), (8-8, 9-9), (9-8, 9-9), (8-8, 10-9) or (-1, 0) (0, 0) (1, 0) (0, 1)"

Subtract origin (1, 2) from each coordinate

(1-1, 3-2) (1-1, 2-2) (1-1, 1-2) (2-1, 2-2) =

(0, 1) (0, 0) (0, -1) (1, 0)

**Then he said:**

> "Now rotate these four coordinates using the rotation matrix multiplication, like we have been talking about."

**Finally he said:**

> "Then add the origin coordinates back to each resulting coordinate, and now you have your four rotated Tile coordinates."

From the matrix above, I have (0, -1) (0, 0) (0, 1) (-1, 0)… so I add these to the origin coordinates like he says (1-1, 3+0) (1+0, 2+0) (1+0, 1+1) (2-1, 2+0) =

Rotated coordinates: (0, 3) (1, 2) (1, 2) (1, 2)

But, looking on my rotated shape... it's completely wrong:

Any thoughts why?

Thanks!

# Answer
Your example is stuffed with bugs and inconsistencies, it is really hard to read, but your understanding error seems to be in sentence 4:

> add the **origin** coordinates back to each resulting coordinate

That is not the original coordinates, but the coordinates of the origin that you are rotating around, so `(1, 2)` in the example case.

By the way, should you desire to rotate a piece around the corner between 4 squares instead of the centre of a square you can use an origin where both the X and the Y component end in `.5`, the final results will still be integer.
> 3 votes

# Answer
`(1-1, 3+0) (1+0, 2+0) (1+0, 1+1) (2-1, 2+0)`

That's not adding the origin back, that's adding your offset rotation to the initial values.

Adding the origin back looks like:

```
 (0,-1) (0, 0) (0, 1) (-1, 0)
+(1, 2) (1, 2) (1, 2) (1, 2)
 -----------------------------
 (1, 1) (1, 2) (1, 3) (0, 2)

```
> 2 votes

---
Tags: java, 2d, matrix, linear-algebra
---


title: Where is the source of XNA lighting?

text:
# Question
Title: Where is the source of XNA lighting?
Talking BasicEffects, where is the source of the three directional lights?

When I write this:

```
effect.DirectionalLight0.DiffuseColor = new Vector3(0.5f, 0, 0); // a red light
effect.DirectionalLight0.Direction = new Vector3(1, 0, 0);

```

What does it mean for the direction? From where is it directing?

# Answer
Directional lights have no position. Think of the sun lighting objects on earth. Technically it has a position, but it is so far away that it does not matter.

Therefore a directional light will illuminate based only on the angle between the light's direction and the surface normal.

If you want lights with a position that also have attenuation, you want to use point lights.
> 4 votes

---
Tags: xna
---


# Question
Title: Mapping of positions on images in different frames
I am looking for a possibility to map different positions on a 2D Image which has different frames. Let's say I have an image, consisting of three frames, which shows a spaceship. The first frame shows the spaceship how it is tilted a little bit (say 20 to 30 degree) to the left side. The second frame shows the spaceship just from the top. The last frame shows the spaceship tilted a little bit to the right (the same amount as in frame 1). Now I want to know, where for example the part which is in the middle of the second frame, is in the first and third frame. The following painting should show what I mean (sorry, I am a bad artist):

The red arrows show example positions which I want to match.

The background is the following: I want to have the possibility to take away parts of the image while playing. The problem is: I want that the parts which were taken away, are taken away on every frame at the right position.

I fail to imagine how to approach this problem as I cannot think of a possible solution. Is there a possibility to achieve this goal or is it just impossible?

# Answer
> 0 votes
It is possible and is no rocket science really. However this migh not be the approach you should be looking for.

For this to work you can either process the image to actually tilt it in 3d by 20 degrees or so, or just make sure your artist has some sick skills of matching reality.

To rotate the object in 3d you multiply each vertex by a transformation matrix. In your case it's only a rotation matrix - good for you. Then you will need to project the 3d space onto a 2d plane. Just get rid of the Z axis. It's that simple :) (granted it's all top down).

Next just multiply any point you wish by the matrix. It will provide new coordinates in 3d. Again, get rid of the Z axis.

It all assumes that the camera remains in the same place and space ship rotates exactly around its main axis which is in the middle.

If you should wish to move the camera aswell then there is something called Matrix multiplication. Shouldn't be too hard either, as basic Algebra is plain easy.

# Answer
> 0 votes
There's no easy way of doing this for 2D images. You might need to ask your graphics artist to draw the parts of the hull below the missing parts and the parts separately for each viewing angle. Having the base hull you can render it and other parts (e.g. wings) on top or below it.

EDIT: Make a thought experiment, if you remove one part of the model, what will be there below it? Where will it be painted? Try making a series of sketches and then see how can you split that in parts.

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


# Question
Title: Partially observable game map — is A* appropriate?
I know very little about game development and I'm trying to wrap my head around pathfinding algorithms.

Consider this setup: an agent is on a 2D map and must find the shortest path to a globally know object but only has information about obstacles in his local vision scope (ie. only immediate obstacles are known, the general layout of the map is unknown).

Also, every move to an adjacent square is expensive and the pathfinding algorithm should minimize the number of moves.

Computational efficiency is also of utmost importance and more important than accuracy.

Is A\* appropriate for this use-case?

# Answer
You should use the D\* algorithm, which is designed for this exact scenario. Specifically, the D\* Lite implementation is the most efficient and simple variant.
> 19 votes

# Answer
Many game AI implementations in that situation will choose to cheat, and give themselves full knowledge of the map, where their human opponent doesn't have that. You can then simply apply A\* to the full map.

How sensible this looks for computer controlled units will depend on things like how maze like the maps are, and if the player is likely to learn the map layouts over time.

If this is for player controlled units you can also prevent the player selecting a destination which they've not explored yet, to force them to explore manually.
> 3 votes

---
Tags: algorithm, path-finding, maps
---


# Question
Title: Does SDL running on Mac OS not recognize Xbox controllers?
I'm trying to learn a bit of SDL, and have been bouncing between Windows and Mac platforms, but am noticing that an SDL program running on my Macbook doesn't recognize the presence of the Xbox controller I have plugged in. I haven't been able to find anything concrete that says one won't work with the other, which is why I'm here.

For reference, here's the code that I'm using to check for the existence of a joystick via SDL:

```
bool hasJoystick = false;
hasJoystick = (SDL_NumJoysticks() >= 1) ? true : false;
if(hasJoystick) {
    for(int i = 0; i < SDL_NumJoysticks(); i++)
        std::cout << "Joystick " << i+1 << "   " << SDL_JoystickName(i) << std::endl;
} else {
    std::cout << "Yo. No joystick here, kid." << std::endl;
}

```

I consistently see the "Yo. No joystick here, kid." message in my console. I'm using SDL 1.2 with, and have copied the framework folder to all the appropriate locations. Also, the controller I'm using is 3rd party, but I'm not sure whether that's relevant.

# Answer
Xbox 360 controllers do not conform to USB HID game controller standards. Even Windows computers require installation of a special, custom driver in order to use them.

Mac computers do not ship with support for Xbox 360 controllers (though they do ship with native support for USB HID game controllers). To use one, you'll need to install a driver for it. Microsoft does not offer such a driver for OSX (at the time of writing), but there are a couple of open source ones (most notably the Tattiebogle one), which Google can locate for you. These drivers sort-of work (again, at the time of writing), but I've had severe enough side-effects from installing them that I've ended up uninstalling them again. And since these drivers don't come with uninstallers or instructions about what files need to be removed, the uninstallation process isn't easy or automatic.

But if you do install a driver for the XBox 360 controller, then they'll show up as regular USB controllers, and the SDL code you've listed above will detect them successfully.
> 7 votes

---
Tags: c++, sdl, macos, xbox-controller
---


title: 2D Particle Physics

text:
# Question
Title: 2D Particle Physics
I am wanting to write small Particle and ParticleEmitter Classes for a HTML5 Canvas Game (Though, just discussing it in pseudo code is fine)

I am not great, at all, at Physics, and I don't want to use any 3rd party scripts/libraries to do this for me. Is there a simple way to do this? The Game is a top-down 2D Game and here is the sort of thing I'm wanting to achieve:

*The Particle is the black ball, and I want it to accelerate up and move to the left until it reaches a specified amount of pixels above the origin, stop, and then accelerate down until it stops and disappears completely*

Any help would be appreciated, I've been searching for a while now and cannot find anything on this.

Thanks

**EDIT: I have implemented a quick mock-up in my game and it works well, but I was just wondering if there was any better, more efficient way to do it (Just because I don't know if this is the proper way, it does not affect performance)**

```
if(_update) {
    _yV += _gravity;
    _y -= _yV;
    _x -= 0.8;

    _diff++;

    if(_diff >= 10 && _loop) {
        _yV *= -0.8;
        _loop = false;
        _diff = 0;
    }else if(_diff >= 20 && !_loop) {
        _update = false;
    }
}

```

# Answer
> 0 votes
It seems from your picture that you want the path to be straight, which is not what would happen if the ball was subject to gravity. Also from your description, it sounds like you want the ball to come to a sudden stop before accelerating downwards again.

Anyway, from what I understand of your problem, here is how I would solve it. If I have misunderstood something, I apologise.

I would store position (vector), direction (normalised vector) and speed (scalar).

```
Vector2 position = Vector(0,0);
Vector2 direction = Vector(1,3).unit();
float speed = 0.0;
const float acceleration = 0.1;
const float y_limit = 100.0;

```

Then, every frame do something like this:

```
position = position + direction * speed;
speed += acceleration;
if( position.y > y_limit )
{
    position.y = y_limit;
    direction.y = -direction.y;
    speed = 0.0;
}

```

You will have to insert your own 2D vector class (or one from a library). If you don't understand vectors, just find a good tutorial and learn the very basics, it will only take 5 minutes.

Hope it helps.

---
Tags: physics, particles
---


# Question
Title: How can I deploy a JavaScript game into the iOS app store?
Unfortunately, I don't have a Mac, so I can't develop for iOS.

I understand that HTML5 apps run in the browser, but is there a way to make an HTML5 app (e.g. a JavaScript game) and get it deployed onto the app store through Apple? How should I package and submit it?

# Answer
You can do this: http://blog.forecast.io/its-not-a-web-app-its-an-app-you-install-from-the-web/

Deploy your web app and provide an easy way for the user to make it a web clip.
> 3 votes

# Answer
Yes. There are many ways to wrap an HTML5 game for distribution on iOS. Solutions include CocoonJS, Game Closure, PhoneGap, and Ejecta.

Examples of HTML5 games on iOS include Onslaught! on iPad and Biolab Disaster on iPhone.
> 14 votes

# Answer
Well as previous answer says, PhoneGap is a solution. Even if he doesn't have mac. PhoneGap hhas own build system
> 1 votes

---
Tags: javascript, ios, html5, appstore
---


# Question
Title: How to attach one sprite to another in LibGDX?
I want to attach one sprite to another so that it is always located at the 'bottom' of the other sprite, regardless of how the main sprite is rotated.

# Answer
> 1 votes
You can have the attached sprite be an entirely separate entity, and just have this entity be moved beneath the original entity each time this entity updates. If you were using scene2d actors, you could have the bottom sprite just be an actor that continuously executes the MoveToAction with a duration of 0, instantly moving beneath the upper sprite (actor).

---
Tags: 2d, sprites, libgdx
---


title: Spawning enemies outside of view

text:
# Question
Title: Spawning enemies outside of view
I'm trying to create a 2d shooter for Android. How do I spawn enemies "above" the screen, so that they "enter" the game screen instead of spawning at the top of it?

I think I need to make a game screen that is bigger than the actual view. How would I do this? I know that negative y-values would work, however that's not really the same.

EDIT: I'm using canvas and bitmaps.

# Answer
As mentioned in the comments, you could spawn the enemies with negative y-coordinates. However, if for some reason you can't do that, you can instead have a "game screen" that is bigger than the size of the view screen. Just render the center part of this game screen, and spawn enemies on the non-rendered outer edges of the game screen.
> 3 votes

---
Tags: 2d, android, shooter
---


# Question
Title: Selling Android apps from Android-Market-unsupported countries
I am in Latvia (which the Android market doesn't support as a country for selling apps from), and I am thinking about the best way of monetizing my app. So far I've come up with these options:

1. Pretend I am from a supported country. Get a bank account there, etc.
2. Use PayPal for in-app purchases. The player gets, say, the first 10 levels for free, but is then asked to pay 0.99$ for the rest of the game. Downside: Players might not feel comfortable entering PayPal details into an app. Android market might not like it either.
3. Making the app free and earning money through advertising. Let's do some calculation here: Say I get 1M free downloads, each user during his playtime would see 10 banners, so 10m / 1000 * 0.3 is about 33k$ if we use AdMob with their 0.3$ per 1000 impressions. On the other hand, if we use PayPal and in-app purchases, we need a \>3% conversion rate to beat this..

What should I do?

**Edit**: From what I just read all over the net, it looks like advertisers will change their eCPM price a lot without telling you. Using in-app PayPal purchases at least allow you to monitor the cash flow.

# Answer
1. You shouldn't do that if Google notices that you are spoofing a country (and they will) then your accounts will be banned and you can't create another one.
2. This might lead to an app deletion by the Google team as the only legal way to do in-app purchases is Wallet / official Google api.
3. You only get paid for clicks not for impressions. I have about 1 Cent per app, with a clicktru rate of nearly 5% which is pretty high and about 40k downloads.

Source: Google Play TOS
> 9 votes

# Answer
That's a very unfortunate situation you're into.

The only legal way I know to do what you want, is to find a publisher to manage the publishing for you. In Japan there's DeNA and GREE, but I'm sure there are lots of companies who would be willing to make business with you if you google something like "Android game publisher".

Most likely, they would be taking one part of your profits, but you may be able to leverage their advertising campaigns and user base and maybe some other goodies.

Whether or not that works for you is completely up to you.
> 4 votes

# Answer
Try ScoreLoop. That's what I'm going to use. Supports paypal stuff.
> -3 votes

---
Tags: android, monetization
---


# Question
Title: Are there any guidelines/articles/tutorials for creating a network protocol for games?
I am currently developing a little 2D sandbox game with multiplayer functionality in XNA 4.0 and the latest lidgren-lib for networking.

I found myself quickly at a point where sending a players position to the server and broadcasting the position of all players to the connected clients isn't enough anymore. So I started to make up a protocol for the game.

I haven't done this before, so I'm wondering weather there're any guidelines/tutorials/articles which guide one through this process. A good starting point for me was the protocol of Minecraft, but this isn't a guide or something but rather a well example which I can adopt at some points.

So, are there any guidelines/articles/tutorials for creating a network protocol for games?

# Answer
> 2 votes
I'm still somewhat new on this, and so I may of missed some things. However, I'll try help regardless.

How is simply sending a position "not enough anymore?" There will always be lag and nothing can be done about that.

A game network protocol is generally unique for every game because only the people making the game knows what needs to be sent and how often to send it. Note that there are a few game engines that send all object data, and as such require virtually no code for networking. This is usually a bad idea for all but the most simplest games due to the amount of data being sent, it quickly faces scaling problems. For example, you don't need to send individual particle data across a network, but such an engine may just do that depending on how the game is coded.

As such, it's rather difficult to make any such tutorial on this subject.

Since this is a sandbox game, let's assume that messages have to be guaranteed since latency isn't such a big issue and most messages need to arrive safely.

Let's have a look at what the minecraft protocol says about player position. http://mc.kev009.com/Protocol#Player\_Position\_.280x0B.29

The player position packet has PacketID, X, Y, and Z. The rest isn't important right at the moment. X,Y,Z are doubles, and PacketID is a Byte. So the Packet is bye + (double * 3). The client sends this to the server at specified intervals, and then the server sends this to the other clients. You may or may not wish to send an "Ok" packet back from the server to the original client.

That's really all there is to it at the basic level of a protocol. You don't want to send the position every frame as you'll flood your bandwidth. The number of updates really depends on the game.

There are more advanced techniques to dealing with lag, such as prediction. http://en.wikipedia.org/wiki/Client-side\_prediction There are two kinds. First is the client doing actions without checking if it's valid by the server. Generally you want to do this for everything, because otherwise you'll have to wait for the server to respond before you jump or move. Not good. The second is predicting what other clients are doing. If someone is falling, it's pretty easy to predict what's going to happen - he'll keep falling until he lands on something or falls out of the game world. As such, you can predict his current position before the server can even give it to you and then update as needed.

```
    Vector3 Position2UpdatesAgo = new Vector3(0,0,0); //Packet received from server.
    Vector3 PositionLastUpdate = new Vector3(1,0,0); //Packet received from server.
    // We have not received the current position from the server, so
    // let's try predict where he will be and move him in our local client.
    Vector3 Position = PositionLastUpdate = Position2UpdatesAgo + (PositionLastUpdate - Position2UpdatesAgo);
    // Position = Vector3 { x = 2, y = 0, z = 0 }

```

You can further save bandwidth by only updating every so often and lerping http://en.wikipedia.org/wiki/Linear\_interpolation between the updates. I believe XNA has a lerp function inbuilt. As such, you'd go something like this.

```
    Vector3 Position2UpdatesAgo = new Vector3(0,0,0); //Packet recieved from server.
    Vector3 PositionLastUpdate = new Vector3(1,0,0); //Packet recieved from server.

    int LastUpdateRecievedMS = 1000; // You'd want to use something like MS since game start/computer start.
    int PredictionTime = 250; // Let's say we predict 250ms into the future. Note that "250" isn't correct, it would be a time based of frameTime and ping.

    Vector3 FuturePosition = PositionLastUpdate = (Position2UpdatesAgo + (PositionLastUpdate - Position2UpdatesAgo) * PredictionTime;

    // We should check to see if CurrentTimeMS() > LastUpdateRecievedMS + PredictionTime. If so, we'll predict further into the future.
    // When we get a new update we'll update all these variables again, and the lerp will help deal with any "jittering" by smoothing out any rough bits,
    // assuming the prediction isn't too far off.
    Vector3 Position = Math.Lerp(PositionLastUpdate, FuturePosition, CurrentTimeMS() / (LastUpdateRecievedMS + PredictionTime);

```

There are likely to be other ways to deal with network optimization. Really though, you cannot update faster then your ping time and only within the limits of your upload and download speeds. Don't forget that the max throughput of a connection is Download/Ping and Upload/Ping. The data you can send will be less due to losses from header information, packets that arrive out of order, lost/dropped packets, incomplete packets, etc. We never really can update fast enough, but we can fool people into thinking that it's happening.

---
Tags: xna-4.0, networking, multiplayer, protocol
---


# Question
Title: In DirectX 11, batching primitives for performance, how does this actually work?
I don't seem to be able to understand this. Microsoft says that one of the possible optimizations of for a Direct3D 11 if to batch primitives draw calls. For example in order to draw say 300 triangles calling the Draw method each time, you would instead pack and Draw them all at once.

The thing I don't get is how you would actually draw them in different locations and everything, because for example, I need one different world transformation matrix for each one. The only thing that comes to my mind is to calculate everything on the CPU and set the values for each vertex manually, however this approach doesn't seem like it would be a very good code optimization to me.

I feel like I'm missing something but I can't find the answer anywhere. The question is: how would you be able to pack things in a draw call without needing a render state change, and still get objects in different locations?

Note that I am not asking for pieces of code here, I'm primarily looking for a theorical answer to this.

# Answer
> 5 votes
There is many ways to do Batching. But for DX11, Instancing is the best choise, and it´s realy efficent and easy to use!

there is plenty of resources on DX11 instancing :

Rastertek instancing
MSDN Instancing reference

How it works is that you create an extra Buffer containing all the worldtransform matrixes. that you pass to the shader.

from there, you will get a "perlayout" matrix, that corresponds to each instance.

The old way of doing this is via calculating the world position for all the triangles befor drawing them, and then using the view\_projection matrix.

# Answer
> 4 votes
> The only thing that comes to my mind is to calculate everything on the CPU and set the values for each vertex manually, however this approach doesn't seem like it would be a very good code optimization to me.

You might be surprised, then.

Obviously, this will depend on the complexity of the geometry you're drawing and the transformations you're applying to it, but you have to remember that the CPU time consumed by `Draw` calls is not insignificant. It will very quickly add up if you have lots of little batches. So if the geometry and transformations are simple, it can very often make a lot of sense to trade the (relatively expensive) `Draw` calls for (relatively cheap) CPU-based transformations.

This is how XNA's `SpriteBatch` works--it accumulates potentially thousands of sprites into a CPU-based buffer by manually transforming vertices, then it sends them all to the GPU at once. Doing a separate `Draw` call for hundreds or thousands of sprites would bring your framerate to its knees, but calculating the positions of their vertices is easy and fast. It's a huge win.

As Tordin explains in his answer, hardware instancing can let you have your cake and eat it too, and is often a good idea. However, the idea of batching primitives the manual way is a general principle that applies even when hardware instancing isn't available.

---
Tags: c++, directx, optimization
---