# Question
Title: How to implement click-to-move in a 2D game?
Currently I am learning how to use XNA by making a 2D Game. So far I am doing okay, but I want to implement a click-to-move instead of using the keys to walk around but I haven't found any samples around and I am sort of clueless on how to approach it.

I know that XNA works well for xbox controls and keyboard but I haven't seen anything related to mouse interaction at all also I dont really mind about xbox since I am not aiming for anything else other then a PC game.

So what I am looking for is how the click-to-move is implemented, and if the mouse icon displayed in game is also supported by the xna framework or if you have to make it yourself in order to make the current tile glow or display that the mouse is there or something like that.

---

**UPDATE:**

Moving with the mouse is not quite the same, you have to consider obstacles as well at least in my case of what i am planning...

For example i want the clicks to be considered as straight walking forcing the user to navigate himself on the map instead of auto-navigating the user per click so if he clicks past a wall for example it will walk to the wall and stop instead of finding the route to the other side if there is one... another doubt that comes to my mind using the getstate of X and Y for example on a scrolling window will it actually recognize where the mouse is or there will be the need of world-to-screen calculation to disclose where is point B that was clicked by the user ?

# Answer
> 7 votes
*Edit: Okay, I've just read from one of your comments that you don't want automatic navigation. In that case, only consider the final section in this post ("Walking that Path") with the simple case that the list only stores the place where your mouse clicked and clears itself when an obstacle is found in the way. I also just noticed that you mentioned tiles once in the post. In that case there's no need for a visibility graph, the grid itself can be used to run A-star on. Anyway I'm still posting this as a more general solution to the 2D point and click navigation problem.*

What you're asking for is how to do pathfinding on a 2D environment. I've written an article before outlining one technique that is capable of solving that problem. I'll start by laying down a link to the article, and then add a brief explanation of the algorithm.

David Gouveia: Pathfinding on a 2D Polygonal Map

Of course, this is not the only way to solve it. I'm using a visibility graph. You could also use a navigation mesh. Or a grid. The visibility graph has one particular advantage that it always returns the most direct path between points without needing to do any path straightening. And building the visibility graph on top of a polygon you can specify the walkable regions precisely.

**Concept**

The main idea here is to represent your walkable region as a polygon and construct a visibility graph using the polygon's *concave* vertices. If the polygon contains holes you'll use their *convex* vertices too.

Creating a visibility graph means taking every node (or vertex in this case) of the graph and connecting it to every other vertex that it can "see". You need some line-of-sight check to do this. The one I used is built on top of a simple line segment intersection test, with a few added checks.

Then whenever you want to find the path between two locations, you add those temporarily to the visibility graph and just run a classic A\* pathfinding algorithm on it.

Here's what the whole structure looks like:

Where:

* The yellow lines are the polgyon representing where you can walk.
* The white circles are the polygon vertices that make up the visibility graph (nodes)
* The purple lines connect vertices that are in line of sight of each other (edges).
* The light blue line is an example of finding a path between two locations (green dot and red dot).
* The light green lines are temporary edges added to the graph along with the starting and ending nodes in the path (green dot and red dot).

**Implementation**

*1) Representation*

About implementing this, first you need to have a way to represent a polygon for your floor. The following class should be enough:

```
public class Polygon
{
    public class SimplePolygon
    {
        List<Vector2> Vertices;
    }

    List<SimplePolygon> Outlines;
    List<SimplePolygon> Holes;
}

```

*2) Selecting Nodes*

Then you need a way to go through each of the polygon's vertices and decide whether they should be nodes in the visibility graph. The criteria for that is concave vertices in the outline and convex vertices in the holes. I use a function like this:

```
public static bool IsVertexConcave(IList<Vector2> vertices, int vertex)
{
    Vector2 current = vertices[vertex];
    Vector2 next = vertices[(vertex + 1) % vertices.Count];
    Vector2 previous = vertices[vertex == 0 ? vertices.Count - 1 : vertex - 1];

    Vector2 left = new Vector2(current.X - previous.X, current.Y - previous.Y);
    Vector2 right = new Vector2(next.X - current.X, next.Y - current.Y);

    float cross = (left.X * right.Y) - (left.Y * right.X);

    return cross < 0;
}

```

*3) Selecting Edges*

Now you'll need to go through every pair of these vertices and decide if they're in line of sight or not. I used the following method as a starting point for that check:

```
static bool LineSegmentsCross(Vector2 a, Vector2 b, Vector2 c, Vector2 d)
{
    float denominator = ((b.X - a.X) * (d.Y - c.Y)) - ((b.Y - a.Y) * (d.X - c.X));

    if (denominator == 0)
    {
        return false;
    }

    float numerator1 = ((a.Y - c.Y) * (d.X - c.X)) - ((a.X - c.X) * (d.Y - c.Y));

    float numerator2 = ((a.Y - c.Y) * (b.X - a.X)) - ((a.X - c.X) * (b.Y - a.Y));

    if (numerator1 == 0 || numerator2 == 0)
    {
        return false;
    }

    float r = numerator1 / denominator;
    float s = numerator2 / denominator;

    return (r > 0 && r < 1) && (s > 0 && s < 1);
}

```

But had to resort to using a few other hacks for stability on edge cases, so it's not in good condition to post. Still trying to find out a clean and stable solution to the problem.

*4) Construct the Graph and Run A-star*

You'll need to create a visibility graph using those vertices and edges, and run A\* on it. For learning how to construct a graph and apply A\* I recommend studying the following article:

Eric Lippert: Path Finding Using A\* in C# 3.0, Part One

You might then want to encapsulate all of this in a single class, so that you have an easy interface to use, such as:

```
public class Floor
{
    public Floor(Polygon polygon)
    {
        _polygon = polygon;
        BuildGraph();
    }

    public IEnumerable<Vector> GetPath(Vector2 start, Vector2 end)
    {
       // Add start and end as temporary nodes and connect them to the graph
       // Run A* on the graph
       // Remove temporary nodes and edges
    }

    private Polygon _polygon;

    private Graph _graph;
}

```

This way you only need to create a Floor instance and call the GetPath method on it whenever you need to find the path between two locations.

*5) Walking that Path*

Finally you need to make your character walk the generated path. He needs to have some kind of internal memory for that, but it's not too hard to implement that. For instance:

1. Add a List inside the character to store the path he's currently following.
2. On each Update cycle take the first value from the list and move your character towards it.
3. If he gets close enough to the destination, remove the first element from the list and repeat.
4. If the list becomes empty, he has reached his destination.

# Answer
> 3 votes
Well... While you're learning don't forget that Google is your true friend in this endevour.

Step 1 is to get the mouse location -- http://msdn.microsoft.com/en-us/library/bb197572.aspx

Step 2 is to move sprite to Location A to Location B which involves basic physics/movement -- http://www.xnadevelopment.com/tutorials/thewizard/theWizard.shtml

The idea is the same moving the mouse is for getting your destination where the user clicks. You are still going from point A to point B.

What you're describing is an implementation detail which you can determine how you want to handle. I'm assuming your working with some sort of grid. The tiles on these grids will have specific properties like walkability. Attempt to move your sprite one step closer in the direction of the destination, if a tile is not walkable, stop.

If you want your sprite to actually get to the desination you would want to implement an actual pathfinding algorithm which analyzes your tiles walkability.

---
Tags: 2d, xna, c#
---


# Question
Title: How do you find the "best" color palette for a game?
If I want to make a 3D game, and I want all my textures to be 8 bit, to save RAM, that is 256 indexed colors, including "transparent", how do I choose the colors?

Is there any recommended pre-defined palette? (Link?)

The end-rendering would use full colors, based on lighting, ...

# Answer
If I interpret your question correctly, you want to know which 256 colors to pick to a palette to make things look good.

This is called the black magic art of color reduction. There's plenty of ways to perform it, some work better than others, and all of them are wrong, as what you're doing is removing information.

One common way is to place all desired colors into an octree and then reading out the 256 biggest cells; another is to do median-cut of the color space until you have 256 segments.

Easiest solution would probably be to drop all the desired colors into photoshop (or something similar), and convert to 8-bit paletted picture. Photoshop, at least, contains variety of methods to do the conversion.
> 3 votes

# Answer
This is more useful for website design but the theory of how colours work together should be applicable anywhere:

http://colorschemedesigner.com/

If you’re set on 8-bit colour, just remember that you won’t have enough to do lots of intricate shading; your models can end up looking quite flat or cartoony (but that may be the look you’re going for). Wikipedia has a list of some of the palettes other people have used:

http://en.wikipedia.org/wiki/List\_of\_8-bit\_computer\_hardware\_palettes
> 4 votes

# Answer
**A few points:**
Modern video cards and drivers has a texture compression feature that pretty much defeat the purpose of this question. You get good looking textures at low memory and memory bandwidth consumption. You can't compress paletted images in the same fashion.

It is correct that you are not even close to having made a game yet? Then why are you asking such a tech question? Stop stalling on possible future issues and get to work.

**A kind of answer:**
As for making a global 8 bit palette, I think you'd get the best results from something like a table with all the possible combinations of colours with 4 different blue values, 7 red values and 9 green values.

In modern computing colour palettes are used mostly for storing images, png images will often grow a lot smaller when converted to 8 bit, and for a lot of their typical use cases the difference is unnoticeable. But this is almost always done with a pallette generated specifically for that image as that can provide way better results than a standard palette.
> 4 votes

# Answer
I would say it depend on what kind of feeling you would like to achieve. If you would like to have some creepy game you will have differente palette (gray/dark colors), then for game some casual "happy" game.

I think the link Sullivan provided is good, if you need Gameboy like palette.

I can't give you exact colors, nobody can. BUT if you are looking for an inspiration I would recommend http://kuler.adobe.com/

Be aware, colors presented at kuler.adobe.com are usually for web designers. But they might give you some idea.
> 2 votes

---
Tags: color, palette
---


# Question
Title: How to make the paddle stop at the screen edge in my Pong clone?
Well, I'm obviously very new to game dev and Android. I've got a ball bouncing around (successfully detecting screen edge collisions so that the bitmap stays within screen) and a paddle that the user can move left and right with their finger.

At the moment there's a few things wrong with my method, but I will post it as is:

(current method from my paddle class that I use to manage touchevents:)

```
public void onTouchEvents(MotionEvent e, int viewW, int viewH){
        //DETECT PRESS
        if (e.getAction() == MotionEvent.ACTION_DOWN){
            // delegating event handling to the paddle
            handleActionDown((int)e.getX(), (int)e.getY());
        }
        //MOVE GESTURES
        if (e.getAction() == MotionEvent.ACTION_MOVE){
            if (isTouched()){
                //paddle is being dragged
                //Log.i(TAG, "paddle is being dragged");

                //SETTING NEW POSITION
                boolean collision = false; // to check wall collisions

                if (speed.getxDirection() == Speed.LEFT
                        && getX() - (bitmap.getWidth() /2) <= 0)
                {//Left wall collision
                    collision = true;
                    Log.i(TAG, "left wall col");

                }
                if (speed.getxDirection() == Speed.RIGHT
                        && getX() + (bitmap.getWidth() /2) >= viewW)
                {//right wall collision
                    collision = true;
                    Log.i(TAG, "right wall col");

                }

                if(collision == false){ //No wall collisions, no problem
                    setX( (int)e.getX() );
                }

            }
        }
        //PRESS RELEASED
        if (e.getAction() == MotionEvent.ACTION_UP){
            if (isTouched()){
                //no longer being dragged
                setTouched(false);
            }
        }
    }

```

At the moment **when my paddle hits the right side of the screen it stops where it should (without the bitmap going off screen) but the user is unable to drag it back**, presumably because collision is now stuck set at "false" so `setX` is never called again.

**Oddly, when the paddle hits the left side of the screen the bitmap can just be continued to be dragged off screen and the collision is never detected.**

Obviously I can recognize that there are two different issues here and I've had several ideas of how to solve the first, still can't figure out whats wrong with the second.

To solve the first I've tried getting rid of the collision variable all together. I've tried putting setting the x position back at various points

```
//eg. (after right wall collision detected)
setX( (int)e.getX() - 1);

```

or using my toggle x direction method, the same I got working with my ball object

```
//eg ( xDirection = xDirection * -1; )
speed.toggleXDirection();

```

I've tried all kinds of re-positioning of the code that I could think of that would possibly get it working as intended but I haven't been able to figure it out, any help would be appreciated.

# Answer
There's no need to create a special flag about wall collisions. Do something like this (in pseudo-code):

```
newX = event.X;
if(newX < leftBound){
    newX = leftBound;
} else if(newX > rightBound){
    newX = rightBound;
}
paddle.x = newX;

```

So basically restrict the new `X` position to valid positions... that should do the trick.
> 4 votes

# Answer
There are many Java implementation of Pong available. They can give you ideas for solving most logic bugs. Here is a list of a few that I've found with source:

I also have versions from former students that include a fair number of features, including a mind bending panic mode. If you are really interested, I can ask them to post their versions.
> 0 votes

---
Tags: java, android, collision-detection, pong
---


title: Flash/Flex/Air and iOS

text:
# Question
Title: Flash/Flex/Air and iOS
I'm just a little confused with all of the news recently regarding the cancellation of mobile flash, so was hoping for a little help. I've had a search through and can't find the answers to these questions, so any help would be great.

First up, I'm looking to create a game in Flash first, to test whether the concept works as a fun game (on Newgrounds/Kongregate/Facebook etc.). Would it be best to use Flash CS5.5, or Flash Builder?

Secondly, with mobile flash now being discontinued by Adobe, could I still port this game over to iOS through the Flash platform, or would it be better at that point to re-write the whole game using Objective C? (NOTE: I'm not an Objective C developer, but am instead a Javascript and Actionscript dev).

Any help would be great. Thanks!

# Answer
> 2 votes
Embedded flash is no longer supported but you can still run flash nativity. So no Newgrounds/Kongregate/Facebook via flash on your phone. If you want to host it on a server then you should look into the HTML5 canvas, especially since you seem to like javascript.

> Would it be best to use Flash CS5.5, or Flash Builder?

I though that the IDE Flash Builder was part of Creative Suite 5.5? If so then they are the same thing.

> Secondly, with mobile flash now being discontinued by Adobe, could I still port this game over to iOS through the Flash platform, or would it be better at that point to re-write the whole game using Objective C? (NOTE: I'm not an Objective C developer, but am instead a Javascript and Actionscript dev).

Unless its incredibly trivial you want to rewrite if only for performance reasons.

# Answer
> 3 votes
I've heard you can publish native iOS apps from flash. Here's a tutorial. Performance won't be as good as porting it to objective-c, but for many games that won't matter.

Also if you are a programmer you should consider using Flex to compile actionscript directly to SWFs. Saves you having to tool around with the godawful flash timeline. You can also use the lovely free FlashDevelop IDE, and some lovely free game libraries like Flixel.

---
Tags: flash, ios, flash-develop
---


# Question
Title: What advantages are there to the one-port-per-client approach for a multiplayer server?
There are a few older games (Quake III and Hexen II to name a couple) where the server assigns a port per player.

Are there performance advantages to this? I suspect there may be, since Carmack & Co.'s endeavours tend to lean in that direction.

I found this, which doesn't provide many different points of view... unfortunately the Book of Hook (link therein) has been down of late, and I don't know if it will ever become available again. What a waste of valuable oldschool knowledge. (If anyone knows where else this might be available, I would be indebted.)

# Answer
> 4 votes
Depending upon your requirements I can imagine following advantages:

1. Independent buffer size for every port for incoming packets. As long as new packets come in and await the processing you are sure you won't face any massive packet loss if your buffer is full. Usually losses of 2-3 packets are not crucial, TCP will quickly have them resent and UDP-based protocols are usually tolerant to losses. If you have a single buffer than you are at risk that somebody will just "DDOS" your complete queue with packets leading to server overload and malfunction.
2. Having different ports you can easily prioritize certain users: if somebody has 10 ms ping and another 170 it is clear that the first user might require responses much more often. You can also add some type of membership -- gold member can get more packets and hence a better reactive game etc.
3. In case of cheating or hacking it is easier to track back the user if every user has a single port assigned to it. Else you have to look at every packet payload, that might be not as easy (especially if the information is encrypted).

---
Tags: multiplayer
---


# Question
Title: Silverlight player centered viewport example
I am new to game development and i want to use silverlight for it. First of all i want to learn the logic of player centered gameplay. Something like this;

Player character moves in large scaled map but player can see only the viewport (centered on player) like on 3000x3000 px map with 400x400 viewport

what do i need to achive this? Is there a code example or any bookthat contains this? Do i need to use a map generator? (so when player moves it replaces titles according to matrix text file etc)

Thanks.

# Answer
> 0 votes
There are several points you should take care of while implementing a game using Silverlight:

1. Silverlight is not a game engine, nor it is a technology primarily targeting game development (like XNA, for example). You will need to implement more things on your own. the most classical example here is the implementation of the game loop -- it is possible in Silverlight using `Dispatcher` and `Timer`, but this can be tricky (due to multi-threading etc). Just google for "Silverlight Game Loop", there are plenty of good tutorials on that topic.
2. I would generally recommend to read some gamedev tutorial for Silverlight. You will find a plenty of links in this thread. Especially this link to a Silverlight platform tutorial and starter kit (ported from XNA) can be helpful for you.
3. And now to your question! :) You will probably need to use the `ScrollViewer` component from Silverlight core components and manipulate the `ViewPort` properties to reach the scrolling and centering in your application. Just google for "sliding with ScrollViewer" and you'll find many ways how to implement this behaviour.

---
Tags: game-mechanics, silverlight
---


title: How to network this entity system?

text:
# Question
Title: How to network this entity system?
I have designed an entity system for an FPS. It basically works like this:

We have a "world"-object, called GameWorld. This holds an array of GameObject, as well as an array of ComponentManager.

GameObject holds an array of Component. It also provides an event mechanism which is really simple. Components themselves may send an event to the entity, which is broadcasted to all the components.

Component is basically something that gives a GameObject certain properties, and since GameObject is actually just a container of them, everything that has to do with a game object happens in the Components. Examples include ViewComponent, PhysicsComponent and LogicComponent. If communication between them is needed, that can be done through the use of events.

ComponentManager just an interface just like Component, and for each Component class, there should generally be one ComponentManager class. These component managers are responsible for creating the components and initializing them with properties read from something like an XML-file.

ComponentManager also takes care of mass updates of components, like the PhysicsComponent where I will be using an external library (which does everything in the world at once).

For configurability, I will be using a factory for the entities which will read either an XML-file or a script, create the components specified in the file (which also adds a reference to it in the right component manager for mass updates), and then inject them into a GameObject object.

Now comes my problem: I am going to try to use this for multiplayer games. I have no idea how to approach this.

Firstly: What entities should the clients have from the beginning? I should start with explaining how a single-player engine would determine what entities to create.

In the level editor you can create "brushes" and "entities". Brushes are for things like walls, floors and ceilings, basically simple shapes. Entities are the GameObject I have told you about. When creating entities in the level editor, you can specify properties for each of it's components. These properties are passed directly to something like a constructor in the entity's script.

When you save the level for the engine to load, it is decomposed into a list of entities and their associated properties. The brushes are converted into a "worldspawn" entity.

When you load that level, it just instanciates all the entities. Sounds simple, eh?

Now, for networking the entities I run into numerous problems. First, what entities should exist on the client from the beginning? Assuming that both the server and client has the level file, the client could might as well instanciate all the entities in the level, even if they are there just for the purposes of game rules on the server.

Another possibility is that the client instanciates an entity as soon as the server sends information about it, and that means that the client will only have entities that it needs.

Another issue is how to send the information. I think the server could use delta-compression, meaning that it only sends new information when something changes, rather than sending a snapshot to the client at every frame. Though that means that the server must keep track of what each client knows at the moment.

And finally, how should networking be injected into the engine? I'm thinking a component, NetworkComponent, which is injected into every entity that is supposed to be networked. But how should the network component know *what* variables to network, and *how* to access those, and finally how the corresponding network component on the client should know how to change the networked variables?

I'm having huge trouble approaching this. I would really appreciate if you helped me on the way. I'm open to tips on how to improve the component system design too, so don't be afraid of suggesting that.

# Answer
> 14 votes
This is a beast of a question with lots of details, +1 there. Definitely enough to help people who stumble upon it.

I just mostly wanted to add my 2 cents about not sending physics data!! I honestly can't stress this enough. Even if you have it so far optimized that you can practically send 40 spheres that bounce around with micro collision and it could go full speed in a shaking room that doesn't even decrease frame rate. I'm referring to performing your "delta-compression/encoding" also known as data-differencing that you discussed.

**Dead Reckoning VS Data Differencing:** They are different enough and really don't occupy the same methods, meaning that you could implement both to increase optimization even further! Note: I have not used them both together, but have worked with both.

**Delta encoding or data-differencing:** The server carries data on what clients know, and sends only the differences between old data and what should be changed to the client. e.g. pseudo-\> in one example you might send the data "315 435 222 3546 33" when the data is already "310 435 210 4000 40" Some are only slightly changed, and one isn't changed at all! Rather than that, you would send (in delta) "5 0 12 -454 -7" which is considerably shorter.

Better examples might be something that changes a lot farther than that for example lets say I have a linked list with 45 linked objects in it right now. I want to kill 30 of them, so I do that, then send to everyone what the new packet data is, which would slow down the server if it wasn't already built for doing things like this, and it happened because it was trying to correct itself for example. In delta encoding, you would simply put (pseudo) "list.kill 30 at 5" and it would remove 30 objects from the list after the 5th one then authenticate the data, but on each client rather than the server.

Pros: (Can only think of one of each right now)

1. Speed: Obviously in my last example I described. It would be a lot larger of a difference than the previous example. In general I can't honestly say from experience which of those would be more common, as I work a lot more with dead reckoning

Cons:

1. If you're updating your system and want to add some more data that should be edited through the delta, you'll have to create new functions to change that data! (e.g. as earlier "list.kill 30 at 5" Oh no, I need an undo method added to the client! "list.kill undo")

**Dead reckoning:** Simply stated, here's an analogy. I'm writing a map for someone on how to get to a location, and I'm only including the points of where to go in general, because it's good enough (stop at building, turn left). Someone else's map includes the street names and also how many degrees to turn left, is that necessary at all? (No...)

Dead reckoning is where each client has an algorithm which is constant per client. Data is pretty much just altered by saying which data needs altered, and how to do it. The client changes the data on its own. An example is that if I have a character that isn't my player, but is being moved by another person playing with me, I shouldn't have to update the data every frame because a lot of the data is consistent!

Lets say I have my character moving in some direction, many servers will send data to the clients that says (almost per frame) where the player is, and that it is moving(for animation reasons). That's so much unnecessary data! Why the hell do I need to update every single frame, where the unit is and what direction it's facing AND that it's moving? Simply put: I don't. You update the clients only when the direction changes, when the verb changes (isMoving=true?) and what the object is! Then each client will move the object accordingly.

## Answers

To be quite frank, read James's post and read what I said about the data. Yes you should most definitely use delta-encoding, but think about also using dead reckoning.

Personally I would instantiate the data on the client, when it receives information about it from the server (something you suggested).

Only objects that can change should ever be noted as being editable in the first place right? I like your idea of including that an object should have network data, through your component and entity system! It's clever, and should work just fine. But you should never give brushes (or any data that's absolutely consistent) any networking methods at all. They don't need it, since it's something that can't even change (client to client that is).

If it's something like a door, I'd give it networking data but only a boolean on whether it's open or not, then obviously what kind of object it is. The client should know how to alter it, e.g. it's open, close it, each client receives that they should all close it, so you change the boolean data, then animate the door to being shut.

As for how it should know what variables to network, I might have a component that is truly a SUB-object, and give it components that you would like to network. Another idea is to not just have `AddComponent("whatever")` but also `AddNetComponent("and what have you")` just because it sounds more organized personally.

# Answer
> 3 votes
Was going to write a comment but decided this might be enough information for an answer.

First, +1 for such a nicely written question with tons of details to judge the answer by.

For the data loading I would have the client load the world from the world file. If your entities have Ids in them that come from the data file then I would also load them by default so your networking system can just refer to them to know which objects it is talking about. Everyone loading the same initial data should mean they all have the same Ids for those objects.

Secondly, do not make a NetworkComponent component as this would do nothing but replicate data in other existing components (physics, animation and the like are some common things to send across). To use your own naming you might want to make a NetworkComponentManager. This would be slightly off from the other Component to ComponentManager relationship you have but this could be instantiated when you start a networked game and have any type of components that have a networking aspect to them give their data to the manager so it can package it up and send it off. This is where your Save/Load functionality could be put to use if you have some sort of a serialization/deserialization mechanism that you could also use to package up data for, as mentioned, giving it to the NetworkComponentManager to package up with the rest of its information and send off to the other player.

Given your question and level of information I do not think I need to go into much more detail, but if anything is not clear please post a comment and I will update the answer to address this.

Hope this helps.

---
Tags: networking, component-based
---


# Question
Title: Character bouncing off ground due to gravity
Implementing gravity in the game, the character keeps bouncing up and down slightly when he hits the ground, upon debugging the character is essentially bouncing on and off the ground. Not quite sure how to iron out the issue any help here would be greatly appreciated.

The constant value

```
private float gravity = 0.09f;

```

adding to the velocity if the character is on the ground

```
if (!isOnGround)
 velocity.Y += gravity;

```

adding the characters overall velocity to the overall position.

```
position += velocity * (float)gameTime.ElapsedGameTime.TotalSeconds;

```

Part of the collision method which determines if the character is on the ground or not.

```
for (int y = topTile; y <= bottomTile; ++y)
            {
                for (int x = leftTile; x <= rightTile; ++x)
                {
                    // If this tile is collidable,
                    TileCollision collision = Level.GetCollision(x, y, tileMap);
                    if (collision != TileCollision.Passable)
                    {
                        // Determine collision depth (with direction) and magnitude.
                        Rectangle tileBounds = Level.GetBounds(x, y);
                        Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);
                        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

                        if (depth != Vector2.Zero)
                        {
                            float absDepthX = Math.Abs(depth.X);
                            float absDepthY = Math.Abs(depth.Y);

                            // Resolve the collision along the shallow axis.
                            if (absDepthY <= absDepthX || collision == TileCollision.Platform)
                            {
                                // If we crossed the top of a tile, we are on the ground.
                                if (previousBottom <= tileBounds.Top)
                                    isOnGround = true;

```

# Answer
> 13 votes
I am afraid I do not fully understand your collision code yet: if there is an off-by-one-pixel error somewhere, it will be hard to spot. But your physics code needs a few fixes already:

* velocity updates should depend on the timestep, even if gravity is a constant
* vertical velocity should be set to zero if on the ground
* adding the “overall velocity” is incorrect; it’s the **average** velocity for the duration of the last frame that needs to be added. This article should explain why.

Leading to the following code:

```
Vector2 oldvelocity = velocity;

if (!isOnGround)
    // This will require tweaking the gravity value
    velocity.Y += gravity * (float)gameTime.ElapsedGameTime.TotalSeconds;
else
    velocity.Y = 0.0;

position += 0.5 * (oldvelocity + velocity)
                * (float)gameTime.ElapsedGameTime.TotalSeconds;

```

---
Tags: xna, physics
---


# Question
Title: Canvas Rotation collision detection on a sprite
I am using this code to detect collisions between two rectangular sprites.

```
intersect: function(other) {
    return this.x < other.x + other.width && other.x < this.x + this.width &&
        this.y < other.y + other.height && other.y < this.y + this.height;
},

```

My question is how can I account for rotation of the sprite. This will only work with the

initial rotational position of the sprite.

Can someone point me in the right direction?

Thanks.

# Answer
Each rectangle has 4 corners and 4 sides. If either corner are within the boundaries of the 4 sides of the other rectangle, or if a diagonal of one rectangle cross a diagonal of the other, they collide.

First, calculate the positions of all the corners, if you know your geometry this shouldn't be too hard.

From here on, vector maths will make it all a lot simpler, go read on the topic if needed. For this purpose we need only points, vectors and the concept of dot products, you can leave the more advanced stuff for later.

Specifically the property that the dot product of two vectors is positive if the angle between them is acute, and negative if it is obtuse is needed.

Look at my beautiful drawing, the angle between vector `a` and `b` is acute, this tells us that the point `b` is pointing to is on the inner side of `c`. `a` and `d` has the opposite property, so `d` is pointing to a point outside the rectangle. Perform such a check for each of the 4 sides.

For the crossing diagonal part, you can check if two line pieces intersect by constructing a quadrilateral first taking an endpoint from the first line, then one from the second line, then the other endpoint from the first line, and finally the other endpoint of the second line. If the figure is convex, the lines pieces intersect. To find if a polygon is convex, you can take the determinant of each side as a vector and the following side, if either all of the results are positive, or all negative the polygon is convex.

One of my previous answers might prove useful: Vector problem: which one is the left / centre / right one?
> 1 votes

# Answer
**Problem**

Checking to see if a corner is included is an interesting approach, and will catch all collisions if the sprites are moving slowly enough, but it will miss some fast-moving thin sprites. Consider this case:

```
    o---o
    |   |b
    |   |
o---+---+-o
|   |   | |a
o---+---+-o
    o---o

```

Here, the tall rectangle `b` and the wide rectangle `a` clearly intersect, but neither contains any vertices other than its own.

**Solution**

The people behind the games N and N+ (Metanet Software) have a brilliant tutorial here -- the long and the short of it is to use the separate axis theorem; for each face on both shapes, compute the normal for that face and project both shapes onto that line

```
aaaaaa          Normal 1:  a
a    a                     a
a    a  bbbbbb             ab  ] overlap by 2
aaaaaa  b    b             ab
        bbbbbb              b

Normal 2:
aaaaaa
        bbbbbb
      ^
      no overlap

```

If the two shapes overlap, then **all** of their projections will overlap. If the two shapes do not overlap, then at least one of their projections will not overlap.

**You're halfway there already**

You might note that testing for overlap in the projection is very similar to what you're already doing for non-rotated rectangles. That's because for aligned rectangles, there are only two normals to project onto -- the X and Y axes.

In any case, the Metanet folks did a great job, and have interactive demos, so definitely check that out. Here's the link again. Or if it's down, use the wayback or google cached copies.
> 1 votes

---
Tags: 2d, collision-detection, physics, javascript, html-canvas
---


# Question
Title: How can I create my mesh so that textures applied to it are NOT rotated 90 degrees in Unity 3D?
I'm trying a really simple test in Unity 3D. I want to render a texture on the simplest plane possible.

So, I've created a two-triangle plane in Blender, then imported it into Unity. From there, I put that mesh on a GameObject, and then drop a texture on top of that. Every time I do this, the texture is rotated 90 degrees when drawn on the plane.

By contrast, if I just create a plane in Unity and drop the texture on that, it is not rotated.

Here is a screenshot showing the simple plane in front of the stock Unity plane:

http://cl.ly/0X052y1G0L1G0a181M1d

I noticed that the triangles in the stock Unity plane's mesh are oriented differently than the ones in the mesh I created (the hypotenuses go from bottom-left to top-right instead of bottom-right to top-left). I went into Blender, rotated the plane 90 degrees, then reimported it unto Unity, but it doesn't seem to make a difference.

What am I missing here?

# Answer
You seem to be missing the UV mapping stage. You have to specify texture coordinates in your modeling program.
> 2 votes

---
Tags: textures, unity, 3d-meshes, rotation, blender
---


# Question
Title: cocos3d versus Unity for simple IOS 3D games?
Wondering if anyone here happens to have experience in doing some simple 3D based games/apps for IOS, using cocos3d & Unity and could give some pointers....questions I have are:

GENERAL

1) It seems currently cocos3d has the most traction in terms of a free 3D games engine for IOS development?

2) If one wanted to step up from the free IOS games engine, to a commercial one it would seem Unity is a popular choice, however you would then not really be doing apple/objective-c development, but rather unity development and pushing a button to pop out an IOS deployable artifact correct?

FOR MY SPECIFIC REQUIREMENT - If I was interested in doing the following:

* develop a relatively simple 3D application for iPhone/iPad
* have a small 'world' such as a room with a few basic items in it (table, cupboard)
* ability to 'drop' a basket ball in the room and have it bounce around based on a physics engine & perhaps some user input (not sure what, lets say control wind direction)
* monitor it and react accordingly - e.g. say if it goes into a net which is in the room then add a point to the scoreboard

At a high level how would one do this using Unity versus using cocos3d, for example:

3) Which would be quicker to develop such a basic iPhone/iPad game/simulation out of Unity/cocos3d?

4) Would 'building your world/room' approach be different? Like in Unity would you build tables/cupboards within a Unity IDE which would make it very quick, whereas with cocos3d would you have to do this programmatically?

5) Would the programming aspect of letting the ball go and monitoring it be different between the two? Or would you roughly in both cases just be setting up world, release ball in certain position, and then engaging physics engine?

6) Any advice/guidance re which tool/approach to use? (Unity versus cocos3d)

7) Re using cocos3d for my requirement, what additional tools would you recommend above/beyond XCode? (e.g. just perhaps some sort of 3D design tool to help model the room and import/save somehow for us in cocos3d)

Basically I'm a hobbyist iOS developer who wants to do some 3d, so the concept of using a free/open-source approach such as cocos3d sounds great as (a) it's free, (b) keep using existing skill set re objective-c etc, BUT the biggest unknown to me is whether by chosing cocos3d would I be giving myself say 20 hours of work to develop a 3d app/animation that could be developed in 1 hour in one of these commercial product (e.g. Unity)?

# Answer
> 4 votes
Both are valid choices, but with Unity3D it's going to be much simpler to achieve what you want, mainly because:

* Unity3D has a much easier content-pipeline. You can simply drop a lot of different image- and 3D formats into Unity and work with them, while cocos3d requires models to be in PowerVR POD format.
* Unity3D has/is a visual editor, which makes it much easier to create your game-world. In cocos3d you would have to come up with your own scene-format and parser.
* Unity3D comes with a 3D physics engine. In cocos3d you would have to integrate the physics engine yourself (for example Bullet).

I really like cocos2d (and 3d), but Unity3D is a much more mature tool for 3D game development than cocos3d is. The 3 points above alone will save you so much time that it's worth buying the Unity license.

Since you can get Unity for free, there's nothing stopping you to try both tools and see what suits you best.

---
Tags: iphone, unity, cocos2d-iphone, ios, cocos2d
---


# Question
Title: A more sophisticated ball-paddle collision algorithm for Breakout?
I have a simple breakout game I'm working on. The collision code is solid; things bounce as they should and don't pass through things or do other funkiness, but the reflection is a bit simplistic. As a result, it's easy to get into a state where the ball gets stuck in a loop such that the last blocks cannot be hit without dying to break the loop.

Currently, the paddle collision code reflects the Y speed, and mirrors the X speed depending on what side of the paddle it hits:

```
        // Check for paddle collisions
        if ((m_ball.rect()).intersects(m_paddle.rect())) {
            double ballCenter = m_ball.rect().getX() + (m_ball.rect().getWidth()/2);
            double paddleCenter = m_paddle.rect().getX() + (m_paddle.rect().getWidth()/2);

            m_ball.setSpeedY(m_ball.speedY() * -1);

            if (ballCenter > paddleCenter) {
                m_ball.setSpeedX(Math.abs(m_ball.speedX()));
            } else {
                m_ball.setSpeedX(-Math.abs(m_ball.speedX()));
            }
        }

```

Is there any way I could make the algorithm more "interesting", and tighten up the control so the ball doesn't keep get stuck bouncing in the same square?

# Answer
**Use a sliding scale to modify the X speed depending on the location on the paddle.**

Set some sort of constant for a max X speed change. If the ball hits on the very right side of the paddle, add this constant to the X speed. If it hits on the very left side of the paddle, subtract this constant from the X speed. If it hits in the very middle of the paddle, do not affect the X speed.

Anywhere in between, use a sliding scale to determine the amount to add or subtract to the X speed.
> 12 votes

# Answer
A lot of break out games will introduce "spin". If the paddle is moving it will influence the X direction of the ball in the direction the paddel is moving.
> 4 votes

# Answer
Jonathan,

I would do as Erick suggests, but I would be careful to make sure the X and Y speed components remain interlocked, otherwise the ball's overall speed will change simply from a collision with the paddle, which is unrealistic physics.

So I would first compute the ball's overall speed from `.speedX()` and `.speedY()` (using the Pythagorean theorem), then compute the new X speed from the position of the ball relative to the paddle, and then set the Y speed dependent on a function of the new X speed and the original overall speed, so that the ball simply changes direction (in an infinite number of possible angles) but always maintains the same overall speed.

To put that more concretely, I would do it like this:

```
if ((m_ball.rect()).intersects(m_paddle.rect())) {
    double ballWidth = m_ball.rect().getWidth();
    double ballCenterX = m_ball.rect().getX() + ballWidth/2;
    double paddleWidth = m_paddle.rect().getWidth();
    double paddleCenterX = m_paddle.rect().getX() + paddleWidth/2;
    double speedX = m_ball.speedX();
    double speedY = m_ball.speedY();

    // Applying the Pythagorean theorem, calculate the ball's overall
    // speed from its X and Y components.  This will always be a
    // positive value.
    double speedXY = Math.sqrt(speedX*speedX + speedY*speedY);

    // Calculate the position of the ball relative to the center of
    // the paddle, and express this as a number between -1 and +1.
    // (Note: collisions at the ends of the paddle may exceed this
    // range, but that is fine.)
    double posX = (ballCenterX - paddleCenterX) / (paddleWidth/2);

    // Define an empirical value (tweak as needed) for controlling
    // the amount of influence the ball's position against the paddle
    // has on the X speed.  This number must be between 0 and 1.
    final double influenceX = 0.75;

    // Let the new X speed be proportional to the ball position on
    // the paddle.  Also make it relative to the original speed and
    // limit it by the influence factor defined above.
    speedX = speedXY * posX * influenceX;
    m_ball.setSpeedX(speedX);

    // Finally, based on the new X speed, calculate the new Y speed
    // such that the new overall speed is the same as the old.  This
    // is another application of the Pythagorean theorem.  The new
    // Y speed will always be nonzero as long as the X speed is less
    // than the original overall speed.
    speedY = Math.sqrt(speedXY*speedXY - speedX*speedX) *
             (speedY > 0? -1 : 1);
    m_ball.setSpeedY(speedY);
}

```

Note: As time goes on, rounding errors will cause the overall speed to drift slowly from its original value. The desired overall speed might be something you want to add as member data to `m_ball` (rather than calculating it each time here), or it might be something you want to allow to speed up and slow down according to other gameplay factors.
> 2 votes

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


# Question
Title: Algorithm to generate small tree-like branches?
I'd like to seed a void map with "branches" of sine waves or any other waveform. Something like:

Know of any algorithm? Has to be one to generate trees or something like that.

# Answer
What is the ultimate purpose of this algorithm supposed to be? Do you want to generate random roads? Branches for a tree? In 2D or 3D space?

The best approach might be to put a bunch of random points on the map, then do a minimum spanning tree. You can then use quadratic or cubic interpolation to make the lines curve into eachother.

Alternately, if you want to generate a tree-like structure in 3-space, you should investigate quaternion rotations, and rotating points about an abitrary axis.
> 4 votes

# Answer
If the your usage is creating landscape (or trees themselves) you can also look into fractal generating algorithms for example:

http://en.wikipedia.org/wiki/Pythagoras\_tree\_(fractal)
en.wikipedia.org/wiki/Fractal
> 1 votes

---
Tags: algorithm, tree
---


title: Ways to define a curve

text:
# Question
Title: Ways to define a curve
**I'm trying to give shapes in my physics engine roundness/ curvature.**

I am aware of various methods for mathematically defining curves; such as bezier-cruves, ellipses, etc. However I am not sure which methods would be most appropriate for use in my physics engine, because speed, feasibility of construction, and flexibility of each method must be considered. I want a system in which a user can easily form fairly complex curves, but still make the intersection calculations simple and fast.

My physics engine is also purely continuous, which means I must be able to calculate the time in which curves will collide with other curves and lines based on a constant linear/angular velocity.

* **What techniques are there for mathematically defining a 2D curve?**
* **What are the advantages/disatvantages of each in terms of speed, flexibility, and simplicity of construction?**
* **Is the technique feasible for an engine where predictability of shape intersection is crucial?**

# Answer
> 3 votes
The curves you describe looks like the Bézier curves.

Usually simpler shapes are used to simulate curves. It is without any doubt possible to test collision with a Bézier curve, but I don't know whether it is more efficient or not than converting it to a set of primitives (lines, rectangles, circles...).

I think it worth testing collisions using the both to see which one is the more efficient.

And even if the simple shapes are faster to test collision with, than using the Bézier curves equation directly, you could still use it in your game editor to create what you need and feel like with Adobe photoshop and convert the curves in a simpler shape set when exporting the level.

As for the circles; they are often used in collision detection system because the are straightforward to test collision with (distance from center, that's all you need).

# Answer
> 0 votes
If your physics engine works solely in terms of straight line segments and circles then the collision detection is as straightforward as you can possibly make it.

The standard technique for rendering Bézier curves is to use de Casteljau's algorithm to reduce them to a series of straight lines (bounding the error, aka distance from the original curve, to e.g. 0.5 pixels).

Put the two together and you have a tried and tested approach which allows you to define curves, is familiar to anyone who's ever worked with paths in Photoshop or the GIMP, and can then be transformed into a suitable structure for collision detection.

---
Tags: collision-detection, mathematics, physics, geometry
---


# Question
Title: Can a 4x4 matrix describe a camera's perspective?
I'm working with a closed-source 3D engine, and it only allows you to set the view projection via a 4x4 matrix. Can this matrix describe the camera's translation, rotation & perspective?

I turned perspective on/off in the engine using a function call, and the matrix values are as follows.

**Without perspective:**

```
1   0   0   -0.0559203194265751
0   1   0   -0.0251115292255206
0   0   1   -0.016129
0   0   0   0.0926626011715394

```

**With perspective:**

```
1   0   0   -0.0560158276396793
0   1   0   -0.0251013526176432
0   0   1   -0.016129
0   0   0   0.0308875337238465

```

# Answer
**Short Answer**

Yes, it can. You should simply calculate a View Matrix and Projection Matrix separately (which are both 4x4 matrices), multiply them together in that order and pass the result (which is still a 4x4 matrix) to your 3D engine.

---

**Long Answer**

Do you know the difference between a View Matrix, a Projection Matrix, and Perspective? You seem to be using those terms a bit too loosely, but they're all different concepts.

---

The **View Matrix** describes *the position and orientation of your camera*, which is usually just a series of translations, rotations and scalings. It works by moving the entire world back *in the inverse direction* around the camera, so that the camera becomes the new origin.

---

The **Projection Matrix** describes how to perform the *mapping between 3D and 2D coordinates*. However, this mapping *does not happen by applying the matrix* \- the matrix *only prepares the values* for the projection. The actual projection is done in a separate step called the *homogeneous divide* (or perpsective divide) which is basically doing the following:

```
(x,y,z,w) => (x/w, y/w, z/w) // Homogenize Vector = Divide everything by last component

```

The are many different *types* of Projection Matrices, with the most popular ones being the Perspective Projection and the Orthographic Projection.

---

A **Perspective Projection** sets up a W value so that when doing the homogenous divide, objects further away from the camera will look smaller. The easiest way to do this is just to divide everything by Z.

The Projection Matrices used in real applications are typically a bit more complex than that because they also have to deal with field of view, aspect ratio and the near/far planes, but the underlying concept is still the same, it just has a few scaling calculations thrown into the mix.
> 14 votes

---
Tags: 3d, camera, matrix, projection, view
---


# Question
Title: Is there a way to balance a binary tree continuously?
In my game I have a tree of objects in 3D space, to which new objects are frequently added.

Over time, the binary tree becomes unbalanced which is a big problem for efficiency as the tree can become quite large. It might even be at risk of stack overflows from deep recursion.

At the same time, it is important to keep branches of the tree close together in 3D space. So I can't arbitrarily swap tree nodes around to balance the tree.

Is there an efficient algorithm that will do the following:

* Allow efficient additions to the tree (O(log n) max)
* Keep the tree approximately balanced as additions are made
* Ensure that branches of the tree contain objects that are close to each other in 3D space (i.e. it works at least approximately as a spatial subdivision tree)

# Answer
It sounds like you need an octree, binary trees really only work for sorting stuff in one dimension. Note that you still will have to travel down multiple branches to find all objects within an arbitrary zone, no data structure can prevent that.

Of course, it would be possible to store items in a standard search tree according to their position on a 3D Hilbert curve, that would be kinda the same thing as an octree, just more convoluted to implement.
> 2 votes

# Answer
The need for nodes to be close to each other just rules out any efficient remodelling of your tree structure (otherwise you could use a Red Black Tree which is 'self balancing for example).

If you want a binary tree structure you can use a BSP structure or a KD-Tree.

Otherwise check out the Octree, the Loose Octree or why not the R-Tree
> 2 votes

---
Tags: algorithm, tree
---


# Question
Title: Calculating normal vector on a 2d pixelated map
I want to know an efficient way to get the normal of the surface of a 2d map. suppose an object hit the map, i want the object to bounce accordingly. The problem is, the "bounding box" of said object is several pixels in size and the map has many curves.

I thought about getting the pixels that collides with the object (don't ask me how) and calculating it's mean, and having the normal to be the line between said pixel and the center of the object

for those familiar with worms, I want to do the same when a grenade hits the map and bounces back

EDIT: I'm not looking for a 100% accurate formula, I want it to be efficient and believable enough

# Answer
First, determine which pixels are boundary/surface pixels. Brute force iterate through all pixels in the map. If they have *any* "air"/"void" pixels bordering them (could be eg. 0 / black pixels in your implementation), they are boundary pixels.

Now for each of these surface pixels, in order to calculate the surface normals, look at it's (two) neighbours. Before we get onto evaluating neighbours, though, there are two ways we can go about running through the surface pixels: one easier, one more efficient.

1. (Easier) Simply keep an unordered list of all surface pixels. As you evaluate each pixel for it's neighbours, you will need to look at all 8 immediate neighbours, checking which already exist in the surface pixel list. This could wind up being really costly, probably O(n\*s), where n is the total number of pixels in the bitmap and S is the number of surface pixels.
2. (More efficient) Find the leftmost, topmost surface pixel in the entire map. Evaluate it for surface pixel neighbours (should be just one). Calc surface normals. Now step to the next unwalked neighbour along the surface. Rinse, repeat, until you've walked every surface pixel. Dealing with floating islands is an edge case you would need to handle separately (but that is a separate question, if you wish to ask it). Because we are not re-evaluating every pixel in isolation for it's neighbours, and are instead re-using the last surface pixels calculations in order to walk to the next surface pixel, this approach should be roughly twice as fast.

So how do we actually use neighbours to find normals during this process? If the pixel in question is A, and it's neighbours are B and C, get the angle of AB and AC. Average these angles. Now get the normal (can usually be done fast by flipping/negating the X and Y components of the averaged vector. Alternatively use a vector rotation approach).

Finally, if you want smoother surfaces (since IIRC the above will give you only about 16 distinct normal angles), you can reapply the same approach to the outputted normals, averaging them further between neighbours. Since you'd likely be precalculating all this prior to the level actually starting, a multipass approach wouldn't cost you anything, really.

**Notes on efficiency**: As in Worms, you are likely re-evaluating surfaces during runtime (that is, CSG is taking place on the terrain). It is probably best to precalculate as much as possible, so your physics can run fast while a player shot is underway. However whenever the terrain is modified, you will have little choice but to perform recalculations (which can then be recached for physics ops). Fortunately though, this will happen between shots, so speed isn't a major concern there, since between shots, physics is usually frozen.
> 3 votes

---
Tags: collision-detection, vector
---


title: 2D Planet Gravity

text:
# Question
Title: 2D Planet Gravity
I'm trying to make a simple game where a spaceship is launched and then its path is effected by the gravity of planets.

Similar to this game: http://sciencenetlinks.com/interactives/gravity.html

I wish to know how to replicate the effect the planets have on the spaceship in this game so a spaceship can 'loop' around a planet to change direction.

I have managed to achieve some bogus results where the spaceship loops in a huge ellipse around the planet or is only slightly affected by the gravity of a planet using Vectors.

Thanks in advance.

p.s I have plenty of coding experience just none to do with game dev.

# Answer
In your case there is an spaceship, which moves affected by the gravity of all the planets. Each planet applies force equal to 'm1\*m2/ r^2' in which m1 and m2 represent masses of spaceship and planet, and r is equal to euclidean distance of planet and space ship. you just have to calculate sum of all the forces applied to ship. from the rules of newton we know 'f = m\*a' where f is total force applied to an object, m is it's mass and a is it's acceleration. from this point you can read this page to learn how to use acceleration to compute velocity and position over time.
> 15 votes

# Answer
Each planet should have gravitational field that pulls any object in its vicinity towards its center. In other words, you should apply a force from the spaceship's position to the planet's center each step of the simulation.

This force depends on the mass of both objects, but in this case, since the mass of the spaceship is probably insignificant compared to the planet's, you can just try out different constant depending on the size of the planet until you get the feel right.

Most importantly, this force grows weaker the larger the distance between both objects. You will do this by dividing by the squared distance between both. After a certain distance you might want to "manually" cutoff and stop applying the force.

Just translate this force into an acceleration, and the basic physic equations should take care of the rest.

In pseudocode

```
force=0
for each planet
    if distance < constant
        force += mass * (planet.xy - ship.xy) / distance^2
apply force to ship

```
> 4 votes

---
Tags: 2d, physics
---


# Question
Title: What are some famous games developed with .NET and/or XNA?
Are there famous games written in .Net and/or XNA?

# Answer
> 25 votes
Schizoid is a pretty successful XBLA game. Does that count? (not really, but its the best I could find)

I think what you mean is are there any AAA-scale games made using XNA and/or XNA GS. To that, the answer is no. The games industry has been very slow move past C/C++ as the gold standard. This isn't for no reason, most AAA games would rather trade all the nice syntax and runtime support for an extra 5FPS and 50MB less RAM usage since both of those directly translate to units sold. Granted there is argument for lower development costs and faster cycles, but thats a hard calculus to use in this industry.

# Answer
> 40 votes
Terraria. It sold 200,000 copies in the first week of release on Steam. It's been in the Steam top 10 sellers list since. I'd say that makes it a popular XNA game.

# Answer
> 33 votes
Magicka is a new one. I played a bit of the demo and it seems pretty good.

# Answer
> 15 votes
It depends on your definition of "famous" :)

* Sol Survivor is a very well polished XNA game, which appears on the Xbox and PC.
* AI War is written on .NET and while not very widely known, is groundbreaking for the scale of gameply it holds.

# Answer
> 15 votes
Bastion. It just won 3 Spike Video Game Awards a couple days ago (not to mention all the other ones it already had - check link).

# Answer
> 11 votes
This thread on the XNA forum has a list of commercial games:

List Of Commercial Games Made With XNA

I'm not sure how many games are 'famous' but it includes some arcade titles like:

Sales data here.

# Answer
> 5 votes
The Dishwasher was made in XNA, as was Flotilla.

# Answer
> 5 votes
Lucidity by Lucas Arts was also written in XNA. Blueberry Garden on Steam, while an indie title, was also written using XNA.

# Answer
> 5 votes
Also, take into account that while not full games, parts of important AAA games have been written in .NET. Supreme Commander used it for it's multiplayer part and Neverwinter Nights Aurora editor was written in .NET.

# Answer
> 4 votes
**Breath of Death VII**

Received a ton of media buzz, including

# Answer
> 4 votes
Funcom's (of Age of Conan/Anarchy Online fame) new game Bloodline Champions is written in XNA. It's currently in closed beta, but they have been quite generous with the beta keys.

# Answer
> 4 votes
What about **Infiniminer** ?

Infiniminer is a voxel based construction sandbox game written in C# using XNA.

It is officially recognised as **the ancestor of Minecraft**.

# Answer
> 3 votes
### Weapon of Choice

Weapon of Choice is an Indie game from Mommy's Best Games. The game is written in C#/XNA. Gamasutra has a great post-mortem where the developer discusses using C# to write a game (he had been using C/C++ prior to going independent).

I don't know if it's considered famous but it did win some awards.

# Answer
> 1 votes
Plain Site had a lot of buzz when it first appeared:

http://www.plainsightgame.com/

# Answer
> 1 votes
One of my favorite simulators, Auran's Trainz is written primarily in .NET.

# Answer
> 1 votes
While not technically .Net, many games made with Unity3D. EA has recently decided to use Unity3D for many of thier new games. The Unity3D engine uses Mono (an open source implementation of .Net) as it's scripting engine. Due to runtime optimizations, script performance as high as 120% native code speeds can be achieved.

For lower end platforms such as consoles (which IMHO makes them unsuitable for hardcore gamers), Mono and by extension Unity supports FULL AOT compilation. This allows games made in a Managed language to run on platforms that do not allow JIT.

As Unity's rendering engine and core components are programmed in C++, you easily break the 60FPS mark as long as you don't do stupid stuff that would ruin the FPS in C++ games as well. Don't iterate through a huge list every frame. Avoid using division, multiplying by 0.5 is 10 times faster than dividing by 2. Don't read from files every frame, cache the data as you need it. Don't run any more code every frame then you need, stick much of your code in methods that are only called when they are needed.

---
Tags: xna, .net
---


# Question
Title: Calculating missile trajectory around orbits before shooting
I'm building a game with Unity3D. It's a Gravity Wars clone. Both player and AI turrets shoot missiles at each other (giving an Angle and a Power variables), trying not to crash missiles on planets. But here's my question: how do I make AI calculate power and angle before shooting his missile, considering a planet's gravity too?

# Answer
> 5 votes
A system like this, with multiple bodies, is going to be chaotic. I don't think that you would be able to solve an equation for it in real-time. The best you can hope is to find a solution using a genetic algorithm;

1: produce a number (e.g.100) of random solutions (angle, power pairs).

2: simulate these solutions.

3: if any of these, end up hitting the target (or coming sufficiently close), Done! otherwise continue.

4: pick best 10 solutions (ones that end up closest to the target)

5: from these 10 solution, create 10 children for each, by randomly adjusting their angle and power.

6: now you have 100 new solutions, got back to step 2

You will need to limit the number of iterations, in case there is no solution to be found, or it is taking too long to search.

Even this approach is not guaranteed to find good solution because; 1. solution might not exist 2. in a chaotic system, small changes to a solution can have a huge impact on the result

# Answer
> 1 votes
You should be able to simulate a shot, without drawing it.

Then you could say, simulate 10 shots, and then take the closest one of the 10.

# Answer
> 0 votes
Given that the trajectory of the missle is based on the inputs of `Angle` and `Power`, you should be able to solve (get an *exact* answer) from an inverse equation.

The basic (psuedo) AI steps are as follows:

1. Pick a random `Power` level. It doesn't matter what the *exact* value is (to an extent), so long as it falls in a reasonable range.
2. Solve the (inverted from the actual pathing) equation to give the *exact* (well, as near as possible with doubles) `Angle`.
3. Pick some a (modifyable) random offset from the `Angle`, to adjust for the '**difficulty**' of the AI.
4. Fire the missle as a player would, at the (random) `Power` and (calculated) `Angle`.

You could of course just have the AI fire at random levels for both inputs, which could produce some interesting results...

# Answer
> 0 votes
How about making it realistic by not having them calculate, but starting with a guess and adjusting appropriately?

When I played Gravity Wars, this is what I did; start with a semi-random power, and adjust accordingly by an increment. Within a couple of shots, you get really close.

---
Tags: ai, unity, projectile-physics, aiming, trajectory
---


# Question
Title: What is the standard procedure for importing animations in Unity?
I need some info about importing game objects from Maya to Unity. I am making 2D Tower Defense game, I have made some basic functionality using dummy objects (cubes and spheres). Now I want to replace these dummies with objects made in Maya. The basic objects for gameplay would include walk of enemy and tower rotation towards it.

So what is the standard procedure of my query, would I need a running enemy object animated in Maya, replace it with my dummy objects, or something like multiple still images of enemy and tower movement, combined in Unity?

# Answer
> 2 votes
Here's a FAQ I wrote last year on importing FBX. At that time, FBX was the standard format for imports of 3D models, and I guess it still is. You can model with Blender (free), and use its FBX exporter, then pull those into Unity. Using the FAQ, you can ensure your FBXes come into Unity *correctly*. At least from Blender, you could export textured models with bone-weighted animations, these would work fine in Unity. Not only that, but you can manipulate models vertex-by-vertex, bone-by-bone and (IIRC) bonegroup-by-bonegroup in Unity, so I guess you could do your own procedural animation provided your pre-FBX model file (in my case, a .blend) was set up correctly.

# Answer
> 1 votes
It has been awhile since I did this for my project, but I know when you import your model into Unity your model will have a list of various components with it, i.e legs, arms, head, etc... Along with those components you have your animation and if you click on the parent node of the model you will get an option in the inspector to "Bake Animations" and that will create the animation whenever the model is called. http://unity3d.com/support/documentation/Manual/Character-Animation.html That will show you how to do the animations within Unity. http://www.youtube.com/watch?v=p25SFf6Kf0g And that will show you how to go about importing them as well. Hope that helps a little bit.

---
Tags: unity, 3dsmax, maya
---


# Question
Title: Java 2D Tile Map and Moving Sprites with threads
I'm having difficulties understanding how to use threads and I'm not sure if my basic structure is right.

This is my Board Class:

```
package mortifera;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JPanel;

public class Board extends JPanel implements Runnable, MouseListener {
    private int posX, posY;
    private Thread thread;
    private Hero hero;
    private Map map;

    public Board(Hero hero, Map map) {
        this.hero = hero;
        this.map = map;

        addMouseListener(this);
        setBackground(Color.BLACK);
        setDoubleBuffered(true);
    }

    public void addNotify(){
        super.addNotify();
        thread = new Thread(this);
        thread.start();
    }

    public void paint(Graphics g){
        super.paint(g);

        Graphics2D g2d = (Graphics2D)g;

        // DRAW MAP. index -> index of map[] array
        int index = 0;
        while(index<(map.getMapWidthInTiles()*map.getMapHeightInTiles())){
            for(int i=0; i<map.getMapWidthInTiles(); i++){
                for(int j=0; j<map.getMapHeightInTiles(); j++){
                    g2d.drawImage(map.getTileImage(index), posX, posY, this);
                    posX += map.getTileWidth();
                    index++;
                }
                posX = 0;
                posY += map.getTileHeight();
            }
            posY = 0;
        }

        // DRAW HERO
        g2d.drawImage(hero.getImage(), hero.getX(), hero.getY(), this);

        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }

    public void run() {
        while(true){
            repaint();
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if(e.getButton() == 1){
            hero.moveTo(e.getX(), e.getY());
        }
    }

```

Followed by my Map Class:

```
package mortifera;

import java.awt.Image;

import javax.swing.ImageIcon;

public class Map {
    private int mapWidth, mapHeight, tileWidth, tileHeight;
    private int[] map =
        { 0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          1,1,1,1,1,1,1,1,1,1,
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0
        };
    private Image[] tileImage;

    public Map(int mapWidth, int mapHeight){
        this.mapWidth = mapWidth;
        this.mapHeight = mapHeight;
        this.tileImage = new Image[2];
        this.tileImage[1] = new ImageIcon(this.getClass().getResource("tile-grass.png")).getImage();
        this.tileImage[0] = new ImageIcon(this.getClass().getResource("tile-mountain.png")).getImage();
        this.tileWidth = this.tileImage[0].getWidth(null);
        this.tileHeight = this.tileImage[0].getHeight(null);
    }

    public int getMapWidthInTiles(){
        return this.mapWidth;
    }

    public int getMapHeightInTiles(){
        return this.mapHeight;
    }

    public int getTileWidth(){
        return this.tileWidth;
    }

    public int getTileHeight(){
        return this.tileHeight;
    }

    public Image getTileImage(int index){
        return this.tileImage[map[index]];
    }
}

```

my Hero Class:

```
package mortifera;

import java.awt.Image;

import javax.swing.ImageIcon;

public class Hero{
    private int[] position;
    private Image image;

    public Hero(){
        position = new int[2];
        position[0] = 0; // X
        position[1] = 0; // Y
        image = new ImageIcon(getClass().getResource("held.gif")).getImage();
    }

    public void setPosition(int x, int y){
        this.position[0] = x;
        this.position[1] = y;
    }

    public int[] getPosition(){
        return this.position;
    }

    public int getX(){
        return this.position[0];
    }

    public int getY(){
        return this.position[1];
    }

    public Image getImage(){
        return this.image;
    }

    public void moveTo(int x, int y){
        while(this.position[0]!=x && this.position[1]!=y){
            if(this.position[0]<x){
                this.position[0]++;
            }
            if(this.position[1]<y){
                this.position[1]++;
            }
        }
    }
}

```

and my Main Class:

```
package mortifera;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        Hero hero = new Hero();
        Map map = new Map(10, 10);
        Board board = new Board(hero, map);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(board);
        frame.setSize(800, 600);
        frame.setVisible(true);
    }

}

```

At the moment a a little map is drawn and my hero...

1. After clicking some time on my screen the game crashes..
2. At the moment the Hero is "teleported" to the point I clicked. I want it to "go" there and know how to do it with a Swing Timer, but not how it works with Threads.
3. Apart from those 2 problems, im very thankful for any hints or critics to my whole concept. Is this, what I'm trying to do, done in this way?

# Answer
> 4 votes
This bit:

```
public void moveTo(int x, int y){
    while(this.position[0]!=x && this.position[1]!=y){
        if(this.position[0]<x){
            this.position[0]++;
        }
        if(this.position[1]<y){
            this.position[1]++;
        }
    }
}

```

Is the crux of your problem. You have to think about game programming in a fundamentally different way than other things. Yes, your character is moving one square at a time (and only in one direction, which is a separate bug), but you're not doing it *over time*.

There are many ways of solving this, but thinking about it in a threaded sense is the wrong way to do it.

In a very basic sense, you need to simulate all of your entities for a frame, draw that frame, then continue to update. That frame is usually somewhere in the range of 1/60th to 1/30th of a second. So if you want your guy to move at X pixels a second, for one "tick" or "frame", you move him that frame's portion. Usually game frameworks have some kind of "game loop" setup where the actual time it took to draw the frame is passed down as a "delta time" value that you use instead of hard coding a frame time.

So in a rough sense, you would have to have an update() method on your guy that represents a single frame's worth of movement, and you do that movement and only that movement. The "while" loop is contained elsewhere (as a trivial case, your "repaint" loop is what you could use).

Just look for documentation on "game loops" and that should point you in a better direction.

---
Tags: 2d, java, multithreading, tilemap
---


# Question
Title: Why do PC versions of games have different memory-related cheats than console versions?
In my "question" about carry weight limitations in Skyrim, MadPumpkin said:

> "You have to understand memory. Picture that I have a variable that can hold up to amount of items ID's. How do I stop the player from carrying 30 instead of the 25 cap? Tell them "you can only hold 25 items" how unrealistic is that!? puts house in pocket"

I don't understand why the PC version doesn't have that memory problem, and furthermore why can't the data be just saved in the saved game and read or written on-demand? Can you please explain it?

On the PC there is a cheat that allows you to by pass the carry limit and the game still works... is this because consoles have different memory architecture?

# Answer
Console versions typically have fewer cheats because it is harder to ensure stability when the players can go in and do debug stuff. Because the platform holders don't want to be known as "unstable", they can fail you if your game crashes for any reason.

There is no central authority for PC games, so cheats don't carry as bad of a side effect. Also the PC market is filled with "tinkerers" who tend to understand what "unsupported" really means.
> 5 votes

---
Tags: game-design
---


# Question
Title: How tightly should I stick to entities in a component based game?
I apologize if the question is a little vague, It was hard to explain it in a short sentence.

I'm currently writing a component based game, it's getting along great but I'm starting to wonder how tightly I should stick to "the rules". Actually, I'm not even sure what the rules are!

It's clear that every interactive gameobject should be an entity. But what about the level elements? I'm using a tile based system, should every tile be an entity? I do have a GraphicsComponent ready with all it's displaying goodness that I need to display them. But coming from inherritance, it just feels strange threating a "gameobject" the same as a level element.

It also feels like I'm dumping everything in a big empty space right now, there is no dedicated environment for different game elements. Where a tile normally is part of a map, and an object normally is part of a world. The tiles and objects are now thrown in the same place.

Same goes for interface components, I was in need of animated button, and that GraphicsComponent looked very tempting again.

---

How is this usually handled in component based games? Most articles online only mention the use of components for gameobjects, and looking into other component engine source code gives me a headache.

# Answer
The main reason for choosing composition over inheritance is flexibility, as most languages allow you to vary the sub-objects of an object at run time easily and arbitrarily, whereas inheritance is fixed at compile time. However, other methods, such as using inheritance, or even just using compile-time composition, is usually less verbose and less error-prone. You just have to know when you need one and when you need the other.

Why should every interactive gameobject should be an entity? Partly because you have so many different permutations of entity properties that it's impractical to create a class for each one. Partly because you might want to define these permutations in data rather than in code. Perhaps it's partly because you want to be able to change them at runtime.

Does this apply to a tile in your game? Probably not. A tile's properties do change based on data, but it's the values that change, not the types of values you need. It's unlikely you need a large number of classes to represent your different types of tiles. I'd probably just have a single tile class, as I can't see the need for more.

> Same goes for interface components, I was in need of animated button, and that GraphicsComponent looked very tempting again.

If your GraphicsComponent already does the job, you may as well use it. Just be aware of the cost of doing so - is the code more complex than the alternative? Would you perhaps gain by factoring out the rendering code into something your interface can use directly instead of via a component? Is it perhaps easier to hold a hard reference to the component as a compromise between the 2 systems? Use what works for you, given your needs and your code.

> How is this usually handled in component based games?

"Usually" is a dirty word when it comes to component based games because there's nothing resembling a consensus on how to make them this way yet. However the main system I'm familiar with, Unity 3D, tries to use components for pretty much everything. It works quite well, but at the price of some additional complexity in terms of making it hard to track interdependencies and the like. So some people bypass this and create their own traditionally coded system within 1 game object, and that works for them also.
> 4 votes

# Answer
The answer depends entirely on what you mean by "entity". What makes something an *entity*?

The whole point of components is that you can give real substantive definitions to these concepts. That way, you don't have to use the "entity" class for everything that can move the way many engines do.

You talk about a "level element". What is that? What does it mean for something to be a "level element," and how is that different from the behavior of an "entity?" You are the only one who can answer that.
> 1 votes

---
Tags: component-based, architecture
---


title: XNA objects not occluding properly

text:
# Question
Title: XNA objects not occluding properly
I have got simple 1x1x1 cube model. I draw 3 of them. They are located at:

1,0,0 2,0,0 3,0,0

I draw them in the same order every time. When I move the camera and look at them from one end everything is fine. If I look at them from the opposite end I can see parts of the cubes that should be occluded by the cubes.

How can I have them draw properly?

# Answer
> 5 votes
The reason why your draw order is messed up is probably because your depth buffer is not being used. With the depth buffer enabled the order in which you draw your meshes makes no difference.

And since you've just stated that you were using a SpriteBatch component, it pretty much confirms that this is the problem:

Link

Quoting that article:

> Before you draw anything in 3D you will probably want to reset these states:
>
> GraphicsDevice.BlendState = BlendState.Opaque;
>
> GraphicsDevice.DepthStencilState = DepthStencilState.Default;
>
> Depending on your 3D content, you may also want to set:
>
> GraphicsDevice.SamplerStates\[0\] = SamplerState.LinearWrap;

In this case, the culprit is GraphicsDevice.DepthStencilState being set to None instead of Default.

---
Tags: xna-4.0
---


# Question
Title: Finding the angle of a line given 2 other lines
I'm trying to implement some 2D vehicle physics. For this to work I have 2 wheels attached to the body of the car. After doing some collisions checks I place the wheels at their new position. Say the first wheel is at (-0.5, 1) and the second wheel is at (0.5, 1) I now have to calculate the angle and position of the body between the wheels. In the given example the angle should be 0. But how do I calculate the angle?

Because pictures make everything easier: The blue lines are the positions of the wheels and the pink line is the body. Given the two positions of the wheels, at what angle is the body in relation to the ground?

# Answer
All you need is atan2:

```
angle = atan2(frontwheel.y - rearwheel.y, frontwheel.x - rearwheel.x);

```
> 1 votes

---
Tags: mathematics, linear-algebra
---


# Question
Title: How to change particle graphics emitted by FlxEmitter?
I'm working with Flixel and attempting to emit "custom" FlxParticles from a FlxEmitter. However, my main issue is that I typically get the default Flixel image emitted instead of my custom graphic.

If I modify the FlxParticle constructor in the Flixel source code like so:

```
public function FlxParticle()
{
    super();
    lifespan = 0;
    friction = 500;
    makeGraphic(4, 4, 0xFFFFFFFF);
}

```

I can get a custom particle (a 4 x 4 white square) to emit from my FlxEmitter.

However, if I write my own class that extends FlxParticle like so:

```
public class EffectParticle extends FlxParticle
{
    public function EffectParticle()
    {
        super();
        makeGraphic(4, 4, 0xFFFFFFFF);
    }
}

```

That class won't work - I will get the default Flixel image instead of my tiny white square. I similar thing happens if I just call "makeGraphic()" on a FlxParticle variable.

**Why does this happen, and other than modifying Flixel's source code or loading in custom graphic (from an embedded image), how can I create my custom particles?**

# Answer
> 0 votes
You have to be sure to specify the number of particles in the third parameter of the FlxEmitter.

If you don't do this, it will ignore your particles and use the default.

Also, set the lifespan in emitter.start(), not elsewhere, otherwise it won't work.

At least, this is all true at the end of 2011 ...

e.g.

var emitter:FlxEmitter = new FlxEmitter(100, 100, 100);

for (i = 0; i \< 100; i++) { emitter.add(new ExplosionParticle()); }

add(emitter); emitter.start(true, 1);

# Answer
> 2 votes
Your code looks right, so here's some things to try to help debug this:

1. Try using an image and loadGraphic(). Does this work?
2. Try extending FlxSprite instead of FlxParticle and see if makeGraphic isn't working for FlxSprite either.
3. What are you seeing on the screen when the particles are emitted? If you're only making one instance of your custom particle to test, I wonder if you're actually seeing the particle emitter, and are forgetting to add(EffectParticle) to your FlxState?

Can you show us the code from your FlxState or wherever the emitter and particles are being added/generated? That might help to find the problem.

---
Tags: flixel
---


# Question
Title: how to draw a dashed curved line to a point in as3?
How can I draw a dashed curved line to a x,y point in as3? Basically I'm creating a game where you have a turret, and I want the arc the turret would fire a projectile along to be displayed as a dashed/dotted line along the arc to wherever the mouse x,y is. Ideally it would use the drawing API, rather than using any bitmap manipulation.

# Answer
> 1 votes
IIRC it's not natively supported. You'll have to look for a library that does this, or write your own. Writing your own would involve a bit of maths, so a 3rd party library may be easier.

---
Tags: actionscript-3
---


title: Calling C++ functions in Lua

text:
# Question
Title: Calling C++ functions in Lua
I'd like to use Lua to write some scripts which should allow me, given the state of certain variables of a specific instance, to determine a number to be assigned to a variable of that instance.

Let me explain: I have a class, which is called Monster. This class contains a boolean variable which is called "Slowed". My script should return a different number depending on Slowed's value.

To do this, I have to push a lot of functions in Lua, for example getSlowed(), and this functions also depend on the kind of instance.

So, I'd like to write a "LuaManager" class which can push the functions in Lua's context... the problem is that I don't know where to start. Anyone has any ideas, or a guide to suggest which I can read?

Thanks.

# Answer
> 5 votes
Writing C++ bindings for Lua is a little more complicated than writing regular C bindings generally. There are things like LuaBind which can automate the process which some people find useful. If you just want to learn how to do simple Lua to C bindings by hand, you should read this (and keep this page handy too). Even if you're not going to do it by hand and decide to go with an automated approach, you should read it anyway so you can understand what's going on under the hood.

Writing bindings for C++ is harder for a few reasons. Lua only uses `void*`s to store your C/C++ objects, so you lose a lot of your type safety. There are also idioms in C++ like RAII that don't translate to Lua as well.

However, if you want to write your own lua bindings for C++ like I did, you can use LuaWrapper. I wrote it for my own game but I put it online in case others find it useful. It handles some of the issues I was running into when using C++ and Lua together, like ensuring that C++ objects are garbage collected properly and making sure when you pass them back and forth between C++ and Lua you always have the right type. You'll need to understand how Lua and regular C fit together to use it though. You can look at this example project I put up that shows how to use LuaWrapper to bind to C++ objects in Lua.

Since you mention getters and setters, I'll also mention I just recently added a second file to LuaWrapper that contains a bunch of common patterns I was using in my code (this isn't in the example project yet). For example, I have a C++ object called a Style which represents how a UI widget will look in various states. To write the getters and setters for that objcet in C++ all I needed to do was add this to create getters and setters in Lua:

```
static luaL_reg Style_Metatable[] =
{
    //                              Type   Member type    Field
    { "idle",           luaU_getset<Style, TextureGroup, &Style::Idle>           },
    { "hover",          luaU_getset<Style, TextureGroup, &Style::Hover>          },
    { "pressed",        luaU_getset<Style, TextureGroup, &Style::Pressed>        },
    { "focusedIdle",    luaU_getset<Style, TextureGroup, &Style::FocusedIdle>    },
    { "focusedHover",   luaU_getset<Style, TextureGroup, &Style::FocusedHover>   },
    { "focusedPressed", luaU_getset<Style, TextureGroup, &Style::FocusedPressed> },
    { "disabled",       luaU_getset<Style, TextureGroup, &Style::Disabled>       },
    { NULL, NULL }
};

int luaopen_Style(lua_State* L)
{
    luaW_register<Style>(L, "Style", NULL, Style_Metatable);
    return 1;
}

```

That allows me to do this in Lua:

```
buttonStyle = Style.new()
Style:idle(buttonIdleBorder)
Style:hover(buttonHoverBorder)
Style:pressed(buttonPressedBorder)

```

# Answer
> 3 votes
Have you had a look at Luabind? See also here and here on SO.

---
Tags: c++, lua
---


# Question
Title: Why is the pixel so popular as the metric unit of a game?
I keep seeing everywhere people using pixels for resolving collisions, angles, distances. I wonder if using the pixel as the metric unit for a game is a good solution, first because you're tying your game logic with implementation, in this case squares in your monitor, second handling more elaborated effects like zoom, rotation becomes more difficult, etc. Isn't adopting integer numbers as your smallest metric unit more flexible and letting the renderer do the pixel operations?

Why the pixel unit is so much popular than integer units? Which are the benefits and drawbacks for each strategy?

# Answer
It is absolutely business-as-usual to decouple physics (and related ops like ray-based picking) from display values. Two common examples (I welcome any others as comments):

1. OpenGL uses the float range 0.0-\>1.0 in x and y, thus abstracting display code from resolution (and thus, pixels).
2. Box2D is also built for such decoupling.

But having said that, it's not always necessary, which is why you see some people simply using 1:1 ratios. OpenGL and Box2D are libraries (write-once-use-many-times), so they *need* to be applicable in a range of circumstances. As such, they wisely do not tie the user into implementation specifics of this sort, since your choice may be totally different from that of another user of the library.

There is nothing to say that an engine may not do perfectly well, if for example the physics are specifically built to work at 1:1 scaling -- or any other fixed scaling, for that matter. You typically still use floating point to deal with fractional values in your physics. (Another alternative is a custom-built fixed-point implementation, if you are running on older hardware -- but that is still a non-integer.)

(Disclaimer: In the particular case of Box2D, Erin Catto has stated that his engine is optimal at a 10:1, physics units to display units ratio. This is based on floating point precision limitations which meant that some optimal ranges had to be chosen for the physics ops to be less "granular" while still supporting relatively high velocities. You can choose your own ratio however. It just provides a smoother experience at 10:1 or higher.)

For 2D games, I normally first consider level size in metres or feet, then consider viewport size such that you know what percentage of the level you want to see at a default (1.0) level of zoom, then decide on the supported screen resolution, and *then finally* use that inform your decision of what your sprites' pixel dimensions need to be.

(Thanks @JoshPetrie, @NicolBolas, @e-MEE for getting us this far on the OP's question.)
> 3 votes

# Answer
Don't know if "everywhere" is true these days, but in good old days (on C64, PC and consoles like NES) the games ran in relatively low resolution (around 300x200 pixels), possibly with special hardware for tiled graphics and sprites.

Back then, it made perfect sense to measure distances and sizes in pixels, as everything was "solid" and there were relatively small amount of pixels available.

Today, even if you're doing a 2d game, you'll probably render it through OpenGL or similar, and can keep your camera dynamic, which in turn decouples pixels from your actual game "physics" entirely.

Of course it may still make sense to think of your visible world in some pixel resolution and do the math that way, if it makes it easier to think about, but there's no longer any actual need.
> 2 votes

---
Tags: pixel
---


# Question
Title: Java Tile Collision Detection not accurate enough
How can I make my isometric tile collision detection more accurate, I'm using the Rectangle class from java to detect collisions but because it's a rectangle it overlaps other rectangles which means clicking on a tile has a chance of selecting the tile next to it and I would like to know how to fix that.

# Answer
> 1 votes
First off, as you stated in your question, you should be using a better representing for the bounding box of each collision. Rectangles are (obviously) incorrect.

Why not create your own `Diamond` class and have each object in your world bound by it? That should provide a better mapping to isometric tiles. As for how to detect if the parallelogram actually contains the point selected, refer to this StackOverflow post: "Parallelogram contains Point".

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