# Question
Title: What's wrong my code to create a GL texture from an SDL_Surface?
I have an issue here with converting an existing SDL\_Surface into an OpenGL texture. The texture gets created, but it's a plain white texture, below is a screenshot of the result:

It seems to me that the SDL\_Surface image data is not being properly cast onto the OpenGL texture. But I'm unsure why. Below is another screenshot, showing the image data of the "Loaded\_Image", which is the existing SDL\_Surface.

I'm just a bit unsure where I'm going wrong. The code seems alright to me:

```
SDLib::Image SDLib::ConvertImage(SDL_Surface* surface)
{
    SDL_Surface *LoadedImage = NULL;
    GLuint tempTexture;
    Image tempImage;
    LoadedImage = surface;

    //Set Width/Height Of Image
    tempImage.width = LoadedImage->w;
    tempImage.height = LoadedImage->h;

    SDL_Surface *image = SDL_CreateRGBSurface(0, LoadedImage->w, LoadedImage->h, 16, 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
    SDL_BlitSurface(LoadedImage, NULL, image, NULL);

    glGenTextures(1, &tempTexture);
    glBindTexture(GL_TEXTURE_2D, tempTexture);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA, image->w, image->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, image->pixels);

    //Finally Set The TempTexture data for our OpenGl Texture to the Temporary Image Struct
    tempImage.texData = tempTexture;

    return tempImage;
}

```

The image itself it supposed to rendering out like this for reference:

# Answer
I think you are using wrong color masks when you create your `image` surface. Try this for a GL\_BGRA texture:

```
SDL_Surface *image = SDL_CreateRGBSurface(0, LoadedImage->w, LoadedImage->h, 16, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);

```

Though, a better solution for loading images would be to use something like this (from gpwiki):

```
// get the number of channels in the SDL surface
nOfColors = surface->format->BytesPerPixel;
if (nOfColors == 4)     // contains an alpha channel
{
    if (surface->format->Rmask == 0x000000ff)
        texture_format = GL_RGBA;
    else
                texture_format = GL_BGRA;
} else if (nOfColors == 3)     // no alpha channel
{
    if (surface->format->Rmask == 0x000000ff)
        texture_format = GL_RGB;
    else
        texture_format = GL_BGR;
} else {
    printf("warning: the image is not truecolor..  this will probably break\n");
    // this error should not go unhandled
}

// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &texture );

// Bind the texture object
glBindTexture( GL_TEXTURE_2D, texture );

// Set the texture's stretching properties
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

// Edit the texture object's image data using the information SDL_Surface gives us
glTexImage2D( GL_TEXTURE_2D, 0, nOfColors, surface->w, surface->h, 0,
                  texture_format, GL_UNSIGNED_BYTE, surface->pixels );

```

That way you can even skip blitting your image to a surface and make a texture right away.
> 4 votes

---
Tags: opengl, textures, sdl
---


# Question
Title: I want to implement free-running movement (like Assassin's Creed) in 2D. What to do?
I would like to implement free-running as popularized by Assassin's Creed, albeit in 2D. What are some specific techniques or algorithms that I can use to achieve free-running in 2D without having to reinvent everything?

I tried to Google for resources, but couldn't really find any leads (no surprise there). Ideally, I'd like to know how did Assassin's Creed did it.

# Answer
> 3 votes
I'm not so sure how looking at Assassin's creed could help, being as it is very firmly rooted in the 3D world when it comes to movement. If you want something like AC's "reach out and grab holes" system, you could look at QWOP's sequel "GIRP" - it's probably too gimmicky to copy for a more traditional game, but the core idea is there. Aside that, Creed had a lot of gap jumping, grabbing onto ledges and shimmying, all of these could probably translate well to 2D in their own style. Prince of Persia might be a good source of inspiration as well.

Also I definitely recommend looking at Super Metroid and the "metroidvania" genre in general if you're looking for traditional side scrolling "free running". There are tons of implementations of wall jumping, trick jumps, etc.

# Answer
> 2 votes
First figure out what specific actions you want to support (e.g. wall-jumping, wall-climbing, sliding, hanging from various parts of the environment, etc.). Then for each of those actions figure out what its constraints should be (e.g. can they only hang from something for a certain amount of time? Do they have to keep moving when they're climbing a wall or they'll fall?) Work out whether they need to manually activate the maneuver or whether it'll happen automatically (e.g. do they have to push a button to grab a rope while they're jumping, or will they grab it automatically as they go by it?) Figure out how close you want them to be to something to grab it or kick off of it. Figure out whether you're going to include the rotation of the player as well as their position and velocity (it'll look better if you do, but it might be frustrating to the player if you make it too challenging to get the rotation right).

Also, try to do the animation really well--watch a lot of reference material (or just find one or two really good examples of what you're doing) to see how bodies actually move when they're doing these things. It can make a world of difference.

---
Tags: 2d, movement
---


# Question
Title: Is there an in memory data store that is feasible for real time, non-networked games?
I would like to know if anyone has recommendations or experience with using an in memory data store for a real time, non-networked game. This is not necessarily for loading levels or saving data, but to be accessed within the game loop as the game is running. Pretty much everything I look at w.r.t. data stores in games refers to networked games like MMOs.

As I am working on my game I find myself building a lot of ad hoc structures to hold various bits of game data and I was thinking it would make more sense to leverage work in this area that would provide a more consistent (and hopefully efficient) retrieval/storage method.

Does anyone have any experience or recommendations on in memory databases or key value stores or document stores that would be reasonable?

For my own purposes, my game is being written in Scala but the answers don't need to be Scala/Java specific.

**EDIT**

To be more specific I am primarily talking about entity data and lists of entities not necessarily things like 3D meshes.

# Answer
> 1 votes
I see two things that need to answered here:

First of all, the simple data structures that you build through normal code are way more efficient than any kind of database, you should as far as possible store your data using those.

If you have a real need to reference data by a string name you should use a search tree, I'm sure you can find a library that implements one.

# Answer
> 1 votes
If you want what is essentially a database, then you might be best off using one. For example http://www.sqlite.org/ can be compiled in with your code, and can store it's data in RAM if you want.

# Answer
> 0 votes
The purpose of anything that you would actually call a "database" is primarily to make searching and finding specific information easy and fast. Unless you have some need to find entities via specialized queries based on many of their properties, you don't need a database. You just need a simple array or map or whatever.

A simple thing like "find entity by name" is something that your programming language's standard library can cover. In C++, the first go-to type for this would be `std::map`.

# Answer
> -3 votes
RDM Embedded has a free evaluation download and the database has pure and hybrid in-memory capabilites. http://raima.com/products/rdme/

---
Tags: data-structure, databases, data
---


# Question
Title: Why can't I import third-party modules I've installed in the python-ogre SDK's interpreter?
**Background Information**

I'm using the python-ogre SDK, located here, under Windows 7. The SDK seems to have its own interface to the python 2.7 interpreter, judging from the fact that the generic interpreter (the one located in C:\python27) must be present in order for the SDK to function.

If the generic python 2.7 interpreter is not installed, the python-ogre interpreter complains that python27.dll is missing.

In addition, modules seem to be highly compartmentalized. The python-ogre modules are only available under the python-ogre interpreter, and not the generic python 2.7 interpreter. The inverse is also true. Modules installed to the generic python installation are not available to the python-ogre SDK interpreter.

I'm not really sure what's going on here, so general clarifications would be helpful.

**The Import Problem**

I recently installed PyYAML and it imports successfully in the standerd python 2.7 interpreter. However, when I try to import it from the python-ogre SDK's interpreter, I get an `ImportError: No module named yaml` error.

What gives?

This may be a general python issue, but it does seem to relate directly to the python-ogre SDK.

As usual, I will be happy to provide additional information upon request. Any advice or help would be greatly appreciated!

**OK GOT IT!**

I just did a sys.path.append('C:\Python27\lib\site-packages'). Apparently all 3rd party modules are installed to this directory.

Is this safe to do? Do I risk creating conflicts between python-ogre and regular ol' python?

# Answer
> 1 votes
It's been a while since I used python-ogre, but I grabbed the package you mentioned.

It looks like they've included their own copy of python.exe, but not the python DLL - I'd assume they just never tested their package on a python-free machine before. At first I thought that this was a custom exe linked with Ogre, but it looks like the same file as my standard ptyhon.exe.

It should be safe to use your site-packages, with two caveats:

1. I would make sure site-packages is in python's path *after* the python-ogre Lib folder, in case they have any special overrides of other packages. (Which is doubtful, but couldn't hurt.)
2. Be sure that you add the path not only when you're running your game, but also when calling any packaging application like py2exe - this will allow py2exe to walk your imports and find everything it needs to bundle in your application.

# Answer
> 0 votes
I'm not sure about the pyEngine itself but there is one big thing I can tell for sure. using 'C:\Python27\lib\site-packages' is not portable. Think how many of your clients have installed python and PyYAML in exactly in the same folder? to make it portable you have to copy/paste PyYAML files into your game project data, and if needed call `sys.path.append` with relative address (from your project binary) to data folder.

---
Tags: python, windows, ogre
---


# Question
Title: Will there be legal issues in using cracked assets for internal development?
While the artwork for my game is being finished, can I use cracked assets for internal prototyping or testing? I am not going publish anywhere outside my company. Does it attract any legal issues?

By "cracked assets" here I mean extracting embedded graphic assets like images and .swf files from a browser cache or an encrypted URL.

# Answer
> 7 votes
I have worked for a company which accidentally shipped unlicensed assets that had been used during internal development. These assets were not ever visible in the shipped game, but they had been overlooked and were accidentally still present amongst the game's data files, and were uncovered and reported upon by the media, and this caused some major legal/licensing issues for the company.

Using assets that you don't have the rights to use -- even exclusively for internal-only development -- is **very** dangerous. It's far too easy to forget to remove those assets before shipping. It's much, much safer to only use assets that you can legally ship, just in case something gets overlooked in the rush to release.

# Answer
> 5 votes
Your best (and probably only sane) option to consult with your company's legal department or, if your company does not have a legal department, talk to a lawyer outside the company.

As others have said, just use temporary assets. It's safer, it should be trivial to do, and it's not like you need to impress anybody if it's for internal use only anyhow. It will also help make sure you remember to get the assets replaced with the final ones.

---
Tags: legal
---


# Question
Title: How do I deal with abstracting collision handling code between entities with differing collision components?
I'm using a component based entity design with `Component`s that hold the data and `System`s that act on entities based on the components they have. Entities are registered to all systems as they are created. If the entity has the list of components the system requires then it'll add it to the system's list to be processed on `Update`.

---

Lets say I have a `BoundingBoxCollisionComponent` a `BoundingCircleCollisionComponent` and an `EdgeListCollisionComponent`.

I have various entities that each have one of these components. For example a `player` entity could have the `BoundingBoxCollisionComponent`, a `bullet` entity could have a `BoundingCircleCollisionComponent` and a `gameworld` entity could have an `EdgeListCollisionComponent`.

Note that my `player`, `bullet` and `gameworld` names aren't types, they're just templates that define components that they all have along with default values for those components.

---

Any collision handling class(es) need to overcome the following issues, that I can't figure out how best to overcome.

1. Obviously the collision detection code is different depending on the exact `CollisionComponent` that 2 entities have. **How can I effectively create classes to handle checking 2 entities for a collision, given that I could add other collision components in the future?**
2. In the scenario above I wouldn't want to check each `Bullet` for a collision with every other `Bullet`. Once the entity is created from the bullet template all notion of it being a bullet disappears, so **How can I manage what entities should be checked against what others?** Do I need to have an `EntityTypeComponent` which would have `Bullet`, `Player`... so I can define in a class somewhere what collides with what, or maybe I could do it at entity creation time (when I know what template is used to create the entity)?

# Answer
For your first question you will obviously have some base functions that handle collision detection for any combination of collision type pairs (i.e. circle/circle, circle/box, circle/ray, box/box, box/ray...). Routing a pair (using a common base class) will require some type introspection or at the very least a type.

For example if every collision component inherited from `BaseCollisionComponent` which had a type property (Circle, Box, Ray...) then you could define a `Collision` function in `BaseCollisionComponent` that takes any pair and based on their type property values routes to the correct collision detection function. This function would handle undefined pairs so when adding new `CollisionComponent`s you would update this to support that type with every other type or it would return an error.

The second question is a case of collision filtering: before performing broad phase collision detection (bounding boxes) or narrow phase collision detection (testing for the exact collision) you want to filter out types (as in game-level types) that shouldn't collide.

A common way to do this to apply a mask to each object, again in a base class you define two bit fields one is the objects collision type and the other is the types you want that object to collide with. So each is an integer where each bit is considered a flag denoting a type. Then when you are comparing collisioncomponents you go to your broad phase only where object one's collision type `&` (as in the binary operator) object two's collides with field doesn't equal zero *or* where object two's collision type `&` (as in the binary operator) object one's collide's with field doesn't equal zero.

I always liked this solution, within your collision function it's just comparing these four integers, defining the fields can be kept at a game level and you can simply define key object's type and leave the configuration to other types (e.g. the player `CollisionComponent` has a type defining player but no collides with field, then the bullet has a type defining bullet and in it's collides with field you set the player type).
> 5 votes

# Answer
I struggled once with this problem. I'm not sure I solved it properly. But to answer your questions:

**1. colliding heterogenous components:**

The collision detection is done through Something like `CollisionDetector(CollisionShape s1, PhyData ph1, CollisionShape s2, PhyData ph2)` like function. this function then reorders the shapes by type:

```
if (s1.type < s2.type)
    return s2.Collide(ph2, s1, ph1).Invert();
else
    return s1.Collide(ph1, s2, ph2);

```

Each CollisionShape must be able to collide with "inferior" types, this way I ensure the system works when new types are added.

**2 Colliding only with the right components:**

My solution was to scrap all the different collision component types and create just a base `CollisionComponentAbstract` and add an array of `CollisionShape` to my `CollisionComponentMultiImpl` while my `CollisionComponentTrivialImpl` has only one `CollisionShape` (no need to have arrays for my bullets)

The collision component (Abstract) receives a list of groups it belongs to (one of my implementation uses a mask) and a list of groups if must ignore (very convenient for friendly fire switches or avoiding bullet collisions).

It is configured with a list of shapes for the initial collision detection (bounding spheres mostly) and a list of collision shapes for deeper collision checks. There are 3 levels in total but you can have more or less.

The process goes more or less like this:

* On collision detection the `ignoreGroup` mask/array of each component close enough is checked with the `belongsTo` mask/array. If no groups are in common then OK.
* Then the `belongsTo` masks are compared and if at least one group is OK then continue.
* Then for each level:
    + For each shape in cmp1 collide with non collided shapes in cmp2. If a Collision is returned keep it
    + if at least one of the components has a higher level of collision shapes increment to the next level where possible and start colliding from scratch
    + else continue colliding at the same level and add each colision to the resulting array.
    + handle the collisions list.

It's a bit more complex than that but this method gives me a few advantages:

* I can add multiple passes for each component and the shapes of one component are never tested against each other if it's a rigid body.
* Components with a higher number of levels can collide with simple components like bullets (which have only one shape) without using any kind of special case.
* I can add multiple collision components with different responders. For example a buff zone around the player will create a dedicated collision component with a responder set to buff any entity responding to the collision if it has the components which can be buffed.

I know this is not the most efficient way of doing it but it's flexible for me and until now my projectiles are pretty slow.

**How it should be done:**

For small fast projectiles, a friend who worked on AAA fps games told me they had collision arrays where one array was dedicated to bullets (position, velocity, type, game data). If I remember well this array is used to do collision detection on the other objects with a first ray cast pass for potential collisions on the bounding shapes. Then there is a second pass reordered by distance on the more detailed models with a dedicated collision resolution. (No shapes used for bullets I think).

Using this principle you can have a system with multiple lists of components (one dedicated to bullets) and when the template for a bullet type is used it will generate a CollisionComponentFSProjectileImpl which will be stored in a dedicated list in your system. Therefore The collision system will always pass another collision component to the CollisionComponentFSProjectileImpl during collision detection which will be able to do collision detection/resolution its own way.

I believe there is nothing wrong with component specialization as long as it doesn't interfere with other unspecialized components and it is properly handled by the systems.
> 2 votes

---
Tags: c#, collision-detection, component-based, entity-system
---


title: Can I add Models Dynamically in XNA

text:
# Question
Title: Can I add Models Dynamically in XNA
i want to add Models (FBX) to My XNA Game without adding them to the "Game Content Project" , so the user could choose his own model , how could i implement this ?

# Answer
> i want to add Models (FBX) to My XNA Game without adding them to the "Game Content Project" , so the user could choose his own model , how could i implement this ?

I'm assuming that the model is created by the user or the third party. If so take a look at this codeplex project. It can run the content compiler at run-time should be pretty easy to replace the GUI with however you want the user to pick their model.

Edit: Codeplex appears to be down but hopefully it'll be back up soon
> 3 votes

# Answer
Are you targeting Xbox or Windows for this project?

If you're targeting Windows, then you can just use the existing content pipeline classes and call them manually to import and process models into your game. When you get to deployment though, I think you'll have to ensure that the pipeline dlls are included (just set Copy Local to true in the reference properties). Not sure if they're part of the XNA redistributable or not.
> 1 votes

---
Tags: xna, models, user-generated-content
---


# Question
Title: Resizing a dynamically resizable widget with a fixed aspect ratio?
I've been trying to figure this out for hours. It is a bit tricky to explain but I'll try to explain it.

I'm making a game where I have a Window with 3 panels in it. The 3 panels must always be squares (width same as height). I can figure out the height of the frame to satisfy this constraint given the width.

The tricky part is, I have a table in the game. The table is in the center of the screen. The table's size is proportional to the height of the OS Game Window. This means when the game is resized on the width, the table does not get any smaller and thus the amount of room available to the Window decreases. The window will appear at the bottom left corner.

The Window needs to be as big as possible without touching the table. The distance from the top left of the window to the edge of the Game Window must be the same as the distance from the Top Right of the Window to the edge of the table and is the same distance as the bottom of the OS Game Window to the bottom of the Window.

Here is an example:

In this example, you can see the edge of the table to the right. You can also see the Window with 3 frames and how the distances between the corners are the same (or as close as I could get it).

Given that I know the size of the table and its location, and the width and height of the OS Window how could I get it to do this? I do not necessarily need code or anything, but I'm more likely looking for the main idea on how I could do this mathematically. As you can see in the image, about 15% of the space is padding, I need to be able to have padding so that it does not consume the maximum area.

Thanks

# Answer
> 2 votes
As far as I can tell from your question, you want your window to have same distance from all sides of screen, that means it's always in the center. to be more clear, center of window and center of the screen should both have same coordinates.

window has 3 panels, and all panels are squares with same size, so we can guess `window.width` is 3 times larger than `window.height`. you also want some padding, so there is some raw value for both width and height of window. let's say these raw values are equal to 85% of screen width and height respectively. using `window.width = 3*window.height` we can compute a new value for both width and height of window. the last step is to use minimum value from these generated values for width or height. here is a pseudo code:

```
 w1 = screen.width * 85%
 h1 = screen.height * 85%
 w2 = h1 * 3
 h2 = w1 / 3

 window.width = min(w1,w2)
 window.height = min(h1,h2)

 alpha = 0.35
 beta  = 0.7

 window.topleft = (screen.width / 2 - window.width * (1-alpha), screen.height / 2 - window.height *(1-beta))
 window.bottomright = (scree.width / 2 + window.width * alpha , screen.height / 2+ window.height *beta)

```

you need to find some good values for alpha and beta(both are between 0..1), alpha value higher than 0.5 will move window to right, while lower alpha values will result in window to be padded to left. also beta value will determine how much window goes near bottom of screen.

---
Tags: c++, algorithm, game-mechanics, gui
---


title: Browser-board-game and server push

text:
# Question
Title: Browser-board-game and server push
I want to start developing a browser game. Not for success, just for the sake of doing it and learning something from it.

Now, a point where I have serious problems figuring out how to deal with it is; how does one player receive message of another player does something that is somehow time-critical.

Easy example for a trading card game; Player 1 plays `The devious flames of hell` and Player 2 has to react to this card by playing `Watery waves` directly afterwards, before the card of Player 1 takes effect (so to say a counter-card).

Of course, I could just request the server every second and see if the other player did something, but I was hoping for a less request-frequent solution, like the server pushes the event of Player 1 playing a card to Player 2.

# Answer
I just stumbled on this the other day -- check out NowJS at http://nowjs.com/ as I think it will give you a nice solution.

From the site...

> NowJS creates a magic namespace "now", accessible by server and client. Functions and variables added to now are automatically synced, in real-time. Call client functions from the server and server functions from client
> 3 votes

# Answer
You can also use long polling in HTTP with Redis, if you want to reduce the pulling on the server. The script essentially "listens" for the "broadcast" from your script.
> 1 votes

# Answer
"somehow time-critical" as in low latency?

WebSocket is the only way https://developer.mozilla.org/en/WebSockets
> 0 votes

# Answer
Try APE project

It's great for low-latency server pushing
> 0 votes

---
Tags: javascript, events, php, server-push
---


# Question
Title: Load state / continue game based on user input
I'm working on a rather simple 2D game, with a pretty small set of values that will need to be preserved for a user to pick up where they left off last time they played.

Rather than saving/loading the state of the game for users to leave/return, I'm considering something akin to what MegaMan did, where a user enters a "password" to resume from their previous state, like so:

How is something like this generally implemented? My two thoughts were

* Build list of all valid passwords and their corresponding states. Reject anything not on the list, and load the corresponding state when correct input is received.
* Represent the state as a binary string, and make that the password. If the user's input parses validly, assume it to be valid and set it to the state.

What are the concerns with each of these approaches, and is there another way to go about this that I've overlooked?

Note: If this question is tagged poorly, it's because this is my first question on gamedev.stackexchange, and I'm not yet familiar with the ta

# Answer
Here are some Pros and Cons for each approach:

---

# List

**Pros**

* No predictable pattern for users to exploit
* You don't need to generate an encoding/decoding

**Cons**

* Only represents pre-defined states
* Gets messy/large when storing many states

---

# Binary representation

**Pros**

* Represent a wider variety of data/states (create a password for any given state of the game)

**Cons**

* Difficulty of implementation

If you are going to use binary representation, I suggest you use something like base16/base32/base64 values depending on your data size.
> 3 votes

# Answer
In my experience the games that use passwords only have one password per level, so you end up with a couple dozen passwords which can be random, or, in some cases, recognizable words.

There are some exceptions though; populous, lotus and sentinel come to mind. All of those use procedurally generated levels, and the "password" basically just encodes the seed for the generation.

From usability point of view, the passwords are a horrible solution. Automatically saved state on exit and "do you want to continue" when re-starting the game is probably the best choice for a simple 2d game. The only positive side that I can think of is being able to take your game state with you and continue playing on some other computer..

But let's say you ignore all of the above and want to store your game state in a password. Let's say you end up having, say, 40 bits of state (or 5 bytes worth). This is short enough so you could just give it as five numbers the user has to input - IP addresses are 4 numbers, and people seem to be able to do that just fine. But let's do some encoding.

Let's say we have an alphanumeric space - 0 to 9, A to Z. That's 36 possibilities. Let's simplify that down to 32 by removing four possibilities that are the most probably confused with other letters - o, i, l and 1. The remaining 32 is 5 bits, so you can encode your 40 bits in 8 characters. Whether this is easier for the user than 5 byte-range numbers, that's up to you. =)
> 0 votes

---
Tags: game-design, algorithm, savegame
---


# Question
Title: To move the object (sprite) in all direction with constant speed in touch direction and to follow the touch path
I am developing this game in cocos2d. I want to move a object(airplane) in all direction with constant speed and it should move and flip in the direction of touch point and it should follow path make by touches like if we make a circle then the object should follow that path and it should flip so that it look like that its moving like real airplane, and i want it should move from one side of screen to other side and again it will come from other side and move towards other side and if we touch the screen then it should move in the touch direction. i have use the code to follow the path but its not working good in my coding object is not moving and not flipping its just appear like that we dragging any object from one position to other, Please any one help me to solve this issue any idea or sample code please provide so that i can make my object to move in all direction with touch.

Thanks in advance.

# Answer
As I explained in chat you have to use one of these algorithms:

```
target = touch.position - airplane.position;
target /= target.length();
target *= some_constant;
airplane.velocity += target;
if (airplane.velocity.length() > max_speed)
    airplane.velocity *= max_speed / airplane.velocity.length();
airplane.angle = atan2(airplane.velocity.y,airplane.velocity.x);

```

---

```
target = touch.position - airplane.position;
target_angle = atan2(target.y,target.x);
if (normalize_angle(target_angle - airplane.angle) < M_PI)
    airplane.angle += constant;
else
    airplane.angle -= constant;
airplane.velocity = max_speed * Vec2(cos(airplane.angle), sin(airplane.angle))

```

and the `normalize_angle` function will convert its input value to a similar angle between 0 and 2\*pi
> 0 votes

---
Tags: cocos2d-iphone, ios, objective-c
---


title: Move an object by rotation AS3

text:
# Question
Title: Move an object by rotation AS3
I am currently trying to move an object (a square) around the stage in 2D space. Think Cuboid but in 2D platformer space, and vertical walls as well as the ground.

The idea is that during each rotation, if any collision occurs, I want the block to move onto that square.

For example, if the "player" is moving left, and there is a wall directly in front of him, he will hit the wall and start to move up the wall instead of on the ground.

There will be edge cases of the player moving left, no block directly in front of him, but a block one width and height to the left of him. I.E. there is a block diagonally up-left of the player, so when the player moves once more to the left, he will collide with the block during the rotation. When that happens, I want to continue the player's movement up the wall as well.

Below is the code of how I am rotation the object and moving it. I do not want to rotate the object around it's center point and move it at along a constant speed. It looks better moving the object with the rotation.

The questions are:

**a**) Is there a better way to accomplish what I am trying to do (I'm sure there is).

**b**) Is there a way to get the positions of each corner while the object is rotating? How I am currently doing it, the only static point is always the bottom left of the player. Since I rotate around that point, and when the rotation has rotated a full 90 degrees, I scaleX and move the object to the new position. So the registration point is always at the bottom left.

Object info: blocks and the player are both 16x16. Their registration points are bottom left.

Game info currently: I just have the player bouncing between the stage boundaries. Hence the moveLeft boolean checks.

```
if (moveLeft){
    rotation -= moveSpeed;
    if (Math.abs(rotation) >= 90){
        if (x == 16){
            moveLeft = false;
            scaleX *= -1;
        }
        else{
            x -= 16;
        }
        rotation = 0;
    }
}
else{
    rotation += moveSpeed;
    if (Math.abs(rotation) >= 90){
        if (x == 624){
            moveLeft = true;
            scaleX *= -1;
        }
        else{
            x += 16;
        }
        rotation = 0;
    }
}

```

If you need anymore information, please let me know. I hope I explained the situation sufficiently.

# Answer
> 3 votes
You could use matrices for your transformation. Using these, it should be simple to rotate around any given point.

Here's a visualization of the process:

Let's assume your cube has its origin at the center of the cube. To rotate it around a corner, you would have to transform the cube, so that the center lies at the desired corner. To rotate around the lower right corner, you would use something like this:

```
matrix.tx = cube.width * -0.5;
matrix.ty = cube.height * -0.5;
matrix.rotate( rotationInRadians );

```

Then you apply the matrix (`cube.transform.matrix = matrix`) and move the cube back by the negative offset.

For the movement, you could have an array containing all offsets for each corner. Then pick the corner-offset depending on the rotation of the cube/rectangle and movement direction.

The same matrix can be used to transform any point. So you could just use a matrix to transform all corner points to get the coordinates of every corner of the cube/rectangle when it's rotated.

---
Tags: actionscript-3, rotation, flash-cs5
---


# Question
Title: Cocos2D-iPhone, how does the Game Loop work in Cocos2D?
Could anyone theoretically explain how the game loop works in Cocos2D and Objective-C?

If you need me to be more specific about what I'm asking, please read on.

I've got a rudimentary understanding of C, pointers, arrays, conditionals, loops, strings, variables, methods, structs etc... procedural thinking makes sense to me.

Cocos2D tutorials tend to introduce Director, Scenes, Layers, Nodes and Actions, then just dive into writing classes and away they go.

I'm missing something: I'm yet to grasp how the Cocos2D game loop operates - I don't know how Cocos2D decides it's time to go render the screen again then wait again for input/events again each frame.

And if there's a lot going on in the classes, how does this game loop interrupt them to say, "sorry guys, gotta render another frame, hold up a bit". Or similar.

What, when, how and where is Cocos2D instigating each "tick" of the game engine to render etc, and how does a game start itself into this game loop environment - and therefore how does one decide to structure classes and messaging activity within this frame work for any given game design?

If you're looking for an example to explain this, please use the original Asteroids game.

# Answer
On iOS 5 Cocos2d uses the `CADisplayLink` (Apple's doc).

It' a timer object that allows synchronizing your application's drawing to the refresh rate of the display.

Cocos2d has a class which receives all dispatches from `CADisplayLink`. It calls `drawScene` on the director class which then calls the scheduler's tics method (which notifies the timers which need to be notified) then it does scene transitions and finally it calls the draw code of the root `CCNode`.
> 4 votes

---
Tags: cocos2d-iphone, game-loop, objective-c
---


title: Making 3D Studio Max Affordable

text:
# Question
Title: Making 3D Studio Max Affordable
3DSMax is pretty expensive. I haven't used it since the late 90s (and remember complaining when the cost hit $1000!) -- it's now around $4000USD, which is pretty pricey. It's also great, and I find working with Blender difficult (the UI is pretty hard to work with.)

Anyway, excluding the 30-day trial, is there any affordable way to legitimately acquire a 3dmax license? With Photoshop, I was able to snag a copy of CS3 at a very reasonable price from someone who upgraded to CS5, but I don't see something similar working here.

What does everybody else do?

# Answer
> 3 votes
Your options:

1. Get the student version: http://students.autodesk.com/?nd=download\_center
2. Download an illegal version (don't do this)
3. Pay full price
4. Use something else
5. Use the trial

You said the trial doesn't work for you but that's the only viable option for what you're asking. If you want to build something commercially with 3ds you better have $4000.

# Answer
> 1 votes
They purchase 3D Studio Max for what it costs because anything else is illegal.

**Updated after receiving clarification from OP that he was not interested in other applications at all**

# Answer
> 0 votes
There is no other way to get 3DSMax without paying the expensive price tag. Aside from pirating of course...

---
Tags: 3dsmax
---


# Question
Title: Support of multiple 3d formats in engine
What is the best practice to add support of loading models from multiple file formats (.obj, .3ds ...)? What class hierarchy should I use (now I have Mesh class( containing vertex, data ) and MeshLoader class ( doing nothing right now ))? I do not want to write loaders by myself, so than I have to copy loaded data into my structure. Possibly you can show some articles explaining it especially Mesh class organization. Thanks in advance.

# Answer
> 4 votes
The format that you load into your game engine should be specific to your game engine, and by specific I mean optimized for your target performance. What you will likely want to do, if you want to support multiple model formats, is to have a processing tool that will convert the different formats into the one for your engine. This is the start of an asset pipeline :)

---
Tags: 3d, models, file-format, model-loader
---


title: Box 2d and really complex big shapes

text:
# Question
Title: Box 2d and really complex big shapes
I intended to use jbox2d for my project. But as I went deeper into it's manual I'd found out that it supports dynamic objects between 0.1 and 10 meters (if use scaling and assume that 0.1 is smallest unit we would have 100 units). I want to create pretty complex and big shapes about 1000 units width.

* So will box2d will handle it?
* Or I should simplify them more to achieve 100 units width max?
* Or my calculations about 100 units width max are wrong? ( But if 0.1 meter is box2d minimum I don't think than I can get smaller unit as measure.)

I had also read about kollider2d, but can't find any info about stress testing it.

As in comment below:

I understand that it doesn't matter if 32 pixels of my system represents 0.1 meter of box2d system nor if it is 50 pixels. With good scale I can manage any value as minimum. I wan't to create objects 1000 times larger than smallest one. And I don't know if box2d will crash or try to handle it but will be very slow or inaccurate.

# Answer
The fact that Box2D can only handle objects between .1 and 10 meters only places the restriction on you that your largest object can only be 100 times larger than your smallest object. Box.2Ds coordinate system can be completely separate from your own, its will just take some multiplication to go back and forth between pixels and meters.

So if "I want to create pretty complex and big shapes about 1000 units width." means you want dynamic objects 1000 pixels wide that is fine with the caveat that your smallest body has to be at least 10 pixels wide.

For example in my game 32 pixels = 1 meter. So the smallest object I could have is 4 pixels across and the largest is 320 pixels. In your case a 100 pixels per meter might be better so that the min size of a body is 10 pixels and the max size is 1000 pixels.
> 1 votes

---
Tags: collision-detection, box2d, collision-resolution
---


title: WebGL geometry calculations

text:
# Question
Title: WebGL geometry calculations
I have a dynamic surface in WebGL, that is animated in vertex shader. I want other objects to interact with this surface (for example, an object riding on dynamic terrain). What's the best way to do this? Should all these calculations be done on CPU? Is there a way to calculate this stuff on GPU?

Basically, what I want is vertex shader with access to other (already transformed) vertices -- that would be perfect.

# Answer
A vertex shader cannot access transformed vertices in WebGL. It can only access uniforms and attributes sent in via one of the draw calls from a bound buffer.

As an example let's discuss how to place a piece of vegetation on a heightfield. Suppose you render the heightfield and transform the terrain vertices in the VS according to this heightfield. Then you render your object and you need to move it by the height it inhabits over that field. A way to do that without CPU work is to pass in an objects center (either via uniform or via attribute) and lookup the heightfield value at the objects center, and then move the vertices vertically by that amount.
> 1 votes

# Answer
You could always represent your original vertices as a texture that is sampled in a fragment shader, and all the appropriate transformations to said vertices can be performed there and rendered to an offscreen render target (i.e. render to texture operation). The data in the resulting rendered texture should then represent the transformed vertices that you're after...
> 1 votes

---
Tags: shaders, animation, webgl
---


# Question
Title: Cleaner implementation of this draw call
Simple static class that will write out a message that is passed in. The SpriteSheet is 256x256 and the A-Z starts at line 240 and the 0-9 starts at 248. Each character is 8x8. I hate the `if (ix >= 32)` and wondered if there is a tidier way of doing this? I'm pleased it's only one `Draw` call, but it looks ugly.

```
public static class Font
{
    private static String chars = "" + //
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ      " + //
        "0123456789.,!?'\"-+=/\\%()<>:;     " + //
        "";

    public static void Draw(string msg, SpriteSheet sprites, SpriteBatch spriteBatch, int x, int y, Color color)
    {
        msg = msg.ToUpper();
        for (int i = 0; i < msg.Length; i++)
        {
            int ix = chars.IndexOf(msg[i]);
            int w = 0, h = 240;
            if (ix >= 0)
            {
                if (ix >= 32)
                {
                    w = 32;
                    h = 248;
                }
                spriteBatch.Draw(sprites.Sheet, new Rectangle(x + i * 8, y, 8, 8), new Rectangle((ix - w) * 8, h, 8, 8), color);
            }
        }
    }
}

```

# Answer
Sometimes math is the answer. if you use division and modulus, you don't have to worry about adding more nested `ifs` once you have 3 lines, or 4 lines.

Remember that modulus wraps from 0 to a certain maximum, then repeats.

The horizontal position in the spritesheet `sprite_x` is the index times char\_width, wrapped at the line width.

The vertical position in the spritesheet `sprite_y` is index / (characters per line) * (character height) + (240, the starting position).

Substituting into your original function, we have

```
msg = msg.ToUpper();
for (int i = 0; i < msg.Length; i++)
{
    int ix = chars.IndexOf(msg[i]);
    spriteBatch.Draw(sprites.Sheet, new Rectangle(x + i * 8, y, 8, 8), new Rectangle(ix * 8 % 256,ix / 32 * 8 + 240, 8, 8), color);
}

```

However. I'd move the constants out a set of const int declarations. This lets you change the configuration, and makes the code more understandable for when you come back in 5 weeks and wonder what exactly the numbers in `ix / 32 * 8 + 240` are.

Suggested:

```
const int LINE_W = 256, FIRST_LINE = 248, CHAR_W = 8, CHAR_H = 8;
static String chars =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ      " + // I lined these up
    "0123456789.,!?'\"-+=/\\%()<>:;  " + // because of my OCD
    "";

static void Draw(string msg, SpriteSheet sprites, SpriteBatch spriteBatch, int x, int y, Color color) {
    msg = msg.ToUpper();
    for (int i = 0; i < msg.Length; i++) {
        var index = chars.IndexOf(msg[i]);
        var sprite_x = index * CHAR_W % LINE_W;
        var sprite_y = index * CHAR_W / LINE_W * CHAR_H + FIRST_LINE;
        SpriteBatch.Draw(sprites.Sheet, new Rectangle(x + i * 8, y, 8, 8), new Rectangle(sprite_x, sprite_y, CHAR_W, CHAR_H), color);
    }
}

```

Also, is there a reason you'd use this over using a custom `SpriteFont` and `SpriteBatch.DrawString` ?
> 2 votes

# Answer
This is a similar way of doing that, but next time your sprite sheets shoud follow the ascii layout to make it easier... :)

```
public static class Font
{
    private static String chars = "0123456789.,!?'\"-+=/\\%()<>:;";

    public static void Draw( string msg, SpriteSheet sprites, SpriteBatch spriteBatch, int x, int y, Color color )
    {
        int ix, h;
        msg = msg.ToUpper( );
        for ( int i = 0; i < msg.Length; i++ )
        {
            h = 240;
            ix = (msg[i] - 'A');
            if ( ix < 0 || ix > 'Z' - 'A' )
            {
                ix = chars.IndexOf( msg[i] );
                h = 248;
            }
            if ( ix >= 0 )
               spriteBatch.Draw( sprites.Sheet, new Rectangle( x + i * 8, y, 8, 8 ), new Rectangle( ix * 8, h, 8, 8 ), color );
        }
    }
}

```
> 0 votes

---
Tags: xna
---


# Question
Title: Simulate race winner based on character attributes
I'm new to game development and I was thinking of starting off with something easy like a top down simulated race game. It will be similar to a horse race, such that there will be betting, and character should win based on their attributes and simulated conditions.

One problem I'm currently facing is how to simulate who wins. Characters will probably have the attributes top speed, acceleration, endurance etc. I don't want the top ranked character winning all the races.

I was looking into probability distributions but I couldn't quite understand how that would help calculate who will win.

I know the winner will be who crosses the finish line first. However how do I calculate characters slowing down, speeding up?

# Answer
> 2 votes
the easiest way is to randomly change attributes at the beginning of each game. say for every player in the game. you have actual attributes, but you'll simulate using some values generated for that exact game (which may be `actual_attribute±10%`).

---
Tags: simulations, distribution
---


title: Is my StatisticManager idea overkill?

text:
# Question
Title: Is my StatisticManager idea overkill?
I'm writing a shmup and I'm working on implementing things like level design and achievements. I have a trigger system that I've implemented which allows me to do basic things and can assist the basic level workflow. However, as it is, this isn't really flexible enough to recognize some other things, such as:

* Determine when an enemy is killed vs. removed from the game
* Not taking damage during some period of time
* Killing enemies using a particular weapon
* Killing enemies in a particular order

Whereas the triggers I have available now basically poll for information, these need to look through a series of events to understand whether the condition is met. So I've conceived a StatisticManager class which would be able to take and store all these events, and provide queries so that new triggers could be written to test for these things. For example, a trigger might ask for an ordered list of enemies killed during some time period, and then determine whether a particular sequence of kills is met.

The design raises a lot of concerns, though, such as determining when to discard / archive data, and how to get statistical data from previous game sessions. Certainly efficiency is a concern.

So my question is: **Does my StatisticManager idea seem appropriate for my needs? What other designs should I consider?**

# Answer
> 1 votes
Are these triggers defined by level, and about how many of them will you plan to have? These questions can help you figure out what is the best approach to efficiency. If your triggers are always active and polling for data, it would only become a problem if you have to iterate through thousands of them each frame (for each possible event in the game). If you only need to iterate through several, it would be fine, though there are several cases where you can optimize a bit more.

Polling for "global" level statistics that apply everywhere (such as # of enemies killed/visited and time passed since last hit) is easier on the game loop than having all triggers on notice, because you only will have to poll for a few items.

However, for triggers to fire immediately based on specific conditions you can have a "sequence reader" that reads from certain lists. These lists will be like a log for several things happening in the level. The enemies themselves could have particular statistics attached to them, like a *killedBy* variable that points to the type of weapon that killed this enemy, and a *timeKilled* variable to let the game know when this particular enemy was killed. Then this data can be added to the particular list when they're killed or removed from the screen.

For particulars of reading sequences, *Take advantage of string matching*. If it's possible to encode some of these stats as 8-bit values, do this as much as possible, then your lists can simply be a group of character values and the sequence reader can read it as a string. For larger values you can split it into two or more characters with bit shifting and you just have to read longer strings. The triggers that need to match patterns will query the appropriate list(s) and see if all matches are met, and if they are, then that condition is met.

If you want to be efficient about this reserve a string buffer of a given size which you can be sure won't overflow during the play of that level. Your StatisticManager sounds like it's more in this direction. I would code it simply as an aggregation of data, and have the sequence reader read from these stats.

At the end of each level collect data from the lists and save it as temporary session data, either directly in memory or as a temporary binary file (another reason why ASCII encoding/decoding can be beneficial) which will be removed when the user closes the program. Archive only the times when the player has reached certain achievements. Detailed session data such as enemy kills or player movements is only useful if you are planning some sort of "replay/record" feature in your game.

# Answer
> 1 votes
In and of itself, your StatisticManager class, sounds like a good idea to encapsulate this sort of logic. However let's address the hurdles you mention.

**Storage**

Backlog size is not what I would call a problem. The reason is that every application that has ever kept a backlog has had to draw the line somewhere, to limit the amount of history it retains. *You have to cut off somewhere*. You need to decide on a backlog size (something, anything!) and work with that constraint in mind, in regards to your game logic. You can adapt it as you move forward in your development processes; other factors will either support or work against your existing choice.

I am not sure I would want to keep data outside of game sessions without there being a very good reason for that. I would keep *just the results* of earlier analyses. It's true that you wont have anything but the results, so you won't, at a later time, know how those results were derived. But primary and secondary storage space aren't infinite either (no matter how *big* it is). Again, *you have to sacrifice somewhere*. If you absolutely had to keep at least certain prior-session data, without losing anything from those sessions, well then that's what file compression is for. Some games do this, and keep a data set that continually grows, eg. save games in some RPGs. But it needs to be darned reasonable if you're going to do that. 1mb per hour is rough. 1kb per hour probably isn't. Even so, it's not an advisable practice.

**Processing**

As you already know, this all depends on the size of the data set. The less data you include in the calculation, the less concern you have. In many cases, the criterion for selection for processing will be time-proximity, i.e. how recent the data is. Which comes down to the same as the above -- just keep the most recent data, up to some predefined limit of storage space or elapsed time. You could store only as much as you'll ever be able to process at once, if processing cost were a bigger issue than storage cost.

You could parallelise this (CPU/GPU). But it sounds like overkill to me, a brute force approach that doesn't really deal with the core of the problem which is, "How do I restrict my data set and still get good results?" Some of the most expansive games ever made were created on a single-CPU, single-core machine with very limited memory. XCOM/UFO and Elite are two such examples. Dwarf fortress is another. That's because those developers knew where to draw the line.

**Conclusion**

Another way to look at this is that you are creating a game with a set of unique servers that host the game, much like an MMO. This being precisely because you have this unusual technical constraint (of storage requirements) that simply makes it unfeasible to do on client systems where you have no say over available storage. If this is the conclusion you come to, it means that you're probably not looking at your problem correctly, and even if you are, you'd need to be in the position to host servers, buy more storage when needed etc. I am guessing you're not in that position right now, because that usually requires solid backing for funding. Any engineering problem is about working to your existing practical constraints, so that solution immediately looks unreasonable.

First and foremost, you need to decide what the hard upper limit to your storage requirements are. From there you can prototype the processing, and see what is or isn't too demanding, set yourself another reasonable limit on processing cost, and move forward with your game from there.

---
Tags: game-design, architecture
---


# Question
Title: Converting cartesian geo-coordinates to isometric (real world map to game map)
I need to create an automated method to convert real cartesian, geo-coordinate data (such as roads and parks), into isometric coordinates as a game map view for use in HTML5 Canvas.

Here is an image of what I mean:

Example Image

Taking into account heavy map distortion in the process to fit they isometric layout. Is this even remotely possible?

# Answer
> 3 votes
1) Convert lat/long to Cartesian coordinates. There a zillion different projections to convert this -- you can see a list here.
For starters, you can use the simplest projection. equidistant cylindrical projection, which assumes latitude and longitude map linearly to X and Y. you can fudge with the offsets

```
function getXY( latitude, longitude ) {
    return {x : 180 - longitude, y : latitude + 90};
}

```

2) Convert from "overhead" to isometric. See this question for how to rotate. isometric means that the y-coordinate is foreshortened so that the diagonal line looks as long as the side of the square, so we have to divide the y-coordinate by the multiplier.

```
function convertIso( x, y ) {
    // m = 1 / sqrt(2);
    var m = Math.sin(Math.PI/4);
    // rotated would be (x*m - y*m, x*m+y*m),
    // but we divide y by m to get the foreshortening
    return { x : x * m - y * m, y : x + y };
}

```

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


title: Where can I find pixel-art artist?

text:
# Question
Title: Where can I find pixel-art artist?
> **Possible Duplicate:**
> Where can I go to find a game graphic artist?

I'm pretty good programmer, and I want to create new pixel-art-game. I know how to program, visualise and optimize the game. But I can't draw! I think there is a lot of people like me... So.. I'm looking for an artist, who can draw pixel-art sprites.

Where I can find "free" pixel-art artist, who just want to create a game (I think that he should have the similar problem, but instead of looking for artist he looks for programmer).

# Answer
> 10 votes
As Valkea mentioned, the PixelJoint and Pixelation fora are good sources for *finding* pixel artists. You might also try the GDNet forums.

**However.**

“Unpaid” posts on these sites tend not to be terribly well received. You’ll need to make a very compelling case to convince anyone to work for free, and you’ll get what you pay for. What many developers don’t know is that **pixel art is extremely time- and effort-intensive**, and animations and tilesets are especially taxing.

The good pixel artists will ask for their worth—a relatively high hourly rate times many hours of work. In my experience, making all of the pixel art required for a complete game will take at least as long as the programming. At best, you might find an upcoming artist looking to do something *pro bono* in order to gain exposure.

Programmers seeking artists seem far more common than the reverse. If you are serious, your goal as a developer should be to **make a fun, high-quality game, even if it looks crappy**. With a demo, you can *demonstrate* to artists that you’re not just looking for someone to give you free artwork, and that you have the skills to possibly make it worth their while.

# Answer
> 4 votes
As I did in this more general question, I would recommend to ask on "pixel art" forums:

Then you can try on forums dedicated to "game creation":

And finally on "art & design forums"...

---
Tags: sprites
---


# Question
Title: Creating 2D billiard game with realistic movement
I'm new to XNA and game programming.

I'm creating a 2D billiard game and I want to add balls with realistic movement (like 3D). Is it possible to achieve this without using 3D models? I only want to use 2D. Please give me examples.

# Answer
I think you are asking how they perform the faux-3d effect on the billiard balls, and is it "real" 3d models or not. I'm not entirely sure what technique they used, but I don't think that its "real" 3d.

I would guess that its a distortion of a stereographic projection of a billiard ball. There is an example here that talks about the distortion technique in flash, but still uses an underlying 3D model to "drape" the texture onto. And another example here that talks about using another pixel bender to create the faux 3d sphere effect, similar to something like this.

Now, Adobe Pixel Benders are functionally equivalent to pixel or fragment shaders. So you should be able to use the references here to do something similar to a sprite in XNA.
> 2 votes

# Answer
> I'm creating 2D billiard game and I want to add balls with realistic movement (like 3D).

Do you just want the ball to slow down due to friction? Do you want the queue to be able to knock it up into the air? Do you want to know what happens when the ball hits a well? Or do you want to know what happens when two balls collide? The word moment is too vague for us to really help you without guessing your needs.

That being said check out this link and this link should cover everything :)
> 1 votes

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


# Question
Title: How to move the ball in straight line in gamesalad?
I have an actor named ball and I want to move it in a straight line which is created by actor ball's X and Y coordinate and cursor's X and Y coordinate. I have Move To behavior in gamesalad but I don't have exact idea how to move the ball with two Cartesian coordinates ball and cursor.

# Answer
> 1 votes
Here's how to solve your issue inside GameSalad:

1. Create 2 Game Attributes: TargetX and TargetY (both should be real)
2. Open your Cursor Actor.
3. Add two Constrain Attribute behaviors to the Cursor: 1 - Constrain self.location.x to touch1.x; 2 - Constrain self.location.y to touch1.y)
4. Add two more Constrain Attribute behaviors to the Cursor: 1 - Constrain TargetX to self.location.x; 2 - Constrain TargetY to self.location.y
5. Open your Ball Actor.
6. Add MoveTo Behavior.
7. Set MoveTo Coordinates to Match Custom Target Coordinates (X = TargetX; Y = TargetY)

Now drop your ball actor into your scene and test away.

# Answer
> 0 votes
I don't know about gamesalad in particular, but the general way you solve this problem is the following:

* Translate the cursor's screen coordinates into your world coordinates (so it's in the same coordinate system as the ball). This is your target position.
* Get the vector from the ball to the target position by subtracting the ball position from the target position. This is your unnormalized direction vector.
* Normalize your direction vector
* Figure your your per-frame movement amount. Usually by multiplying your units/second desired speed by the frame time.
* Multiply your normalized direction vector by the per frame movement amount.
* Add that per frame movement amount to your ball's position.

---
Tags: movement, gamesalad
---


# Question
Title: Weird block selector selection (to floor or not to floor)?
Well, I am creating a Minecraft like engine in XNA, and since I first implemented the block selector (the cube that allows you to select blocks in 3D space) it has always been very inaccurate. Here is what I mean:

And here is the code that does the selecting (note that I have tryed to ceil then floor the vectors but none correct the abnormal positioning of it):

```
private Block GetSelectedBlock()
{
    Block block = new Block();
    block.BlockType = BlockType.none;

    for (float x = Variables.SELECTION_MIN; x < Variables.SELECTION_MAX; x += 0.1f)
    {
        Vector3 targetPoint = camera.Position + (camera.LookVector * x);
        //targetPoint = Util.FloorVector3(targetPoint);
        //targetPoint = Util.CeilVector3(targetPoint);

        blockSelector.UpdatePosition(new Vector3((int)targetPoint.X, (int)targetPoint.Y, (int)targetPoint.Z));
        block = world.GetBlock((int)targetPoint.X, (int)targetPoint.Y, (int)targetPoint.Z);

        if (block.BlockType != BlockType.none)
        {
            blockSelector.Visible = true;
            break;
        }

        blockSelector.Visible = false;
    }

    return block;
}

```

Also the two following screen shots show where the block selection cube is placed when I do call the `blockSelector.UpdatePosition()` function but do not cast the values to integers:

Any ideas what I am doing incorrectly?

Also regarding Blecki's answer here is what I implemented based on his idea:

```
       private Block GetSelectedBlock()
    {
        Block block = new Block();
        block.BlockType = BlockType.none;

        for (float x = Variables.SELECTION_MIN; x < Variables.SELECTION_MAX; x += 0.1f)
        {
            Vector3 targetPoint = camera.Position + (camera.LookVector * x) + new Vector3(0.5f, 0.5f, 0.5f);
            targetPoint = Util.FloorVector3(targetPoint);

            blockSelector.UpdatePosition(new Vector3((int)targetPoint.X, (int)targetPoint.Y, (int)targetPoint.Z));
            block = world.GetBlock((int)targetPoint.X, (int)targetPoint.Y, (int)targetPoint.Z);

            if (block.BlockType != BlockType.none)
            {
                blockSelector.Visible = true;
                break;
            }

            blockSelector.Visible = false;
        }

        return block;
    }

```

It seems to allow you to place blocks alot more accurately but it is still off centre:

# Answer
> 0 votes
I did the following to get accurate block placement:

```
    public Block GetBlock(Vector3 position)
    {
        int x = (int)Math.Floor(position.X);
        int y = (int)Math.Floor(position.Y);
        int z = (int)Math.Ceiling(position.Z);

        Block block = GetBlock(x, y, z);

        return block;
    }

```

# Answer
> 1 votes
There's a better and simpler way to find the closest block under the 'mouse'. XNA provides a ray and an AABB type, and the function Ray.Intersects. Intersects returns the distance to the intersection or null, if there was none. You can test the blocks that may be under the 'mouse/reticle' and pick whichever block is closest. Obviously, checking every block would be terribly in-efficient. You can use a simple tree of bounding boxes to narrow the search down to individual blocks.

Here is some code I ripped out a project of mine that does exactly this. In this example, imagine that 'prism' represents a rectangular prism of blocks, and Prism.Split splits the prism on it's longest axis, unless it's smaller than a threshold, in which case it returns false.

```
    public static void rayTraversal(
        Prism prism,
        Ray ray,
        Action<Coordinate> func)
    {
        Prism? A, B;
        if (!prism.Split(out A, out B))
            _raySubRegion(A.Value, ray, func);
        else
        {
            var ADistance = ray.Intersects(GetPrismAABB(A.Value));
            if (ADistance.HasValue)
                rayTraversal(A.Value, ray, func);
            var BDistance = ray.Intersects(GetPrismAABB(B.Value));
            if (BDistance.HasValue)
                rayTraversal(B.Value, ray, func);
        }
    }

    private static void _raySubRegion(Prism prism, Ray ray, Action<Coordinate> func)
    {
        for (short _x = prism.X; _x < prism.X + prism.Width; ++_x)
            for (short _y = prism.Y; _y < prism.Y + prism.Height; ++_y)
                for (short _z = prism.Z; _z < prism.Z + prism.Depth; ++_z)
                {
                    var Box = GetTileAABB(new Coordinate(_x, _y, _z));
                    if (ray.Intersects(Box).HasValue)
                        func(new Coordinate(_x, _y, _z));
                }
    }

```

This will call the action passed in for every block coordinate that intersects the ray. You should be able to figure out how to make it choose the block closest to the camera.

Another solution is to use a raycasting algorithm, but I'll let someone else write that one up.

# Answer
> 1 votes
Your current method is never going to work 100% of the time, because you're stepping in increments that could occasionally miss the edges of blocks.

You should probably be using a form of raycasting. Because you're creating a Minecraft clone that means all of your blocks are axis-aligned boxes, which makes it extremely easy to determine which blocks are lie along a line in front of the camera.

```
Viewport viewPort = game.GraphicsDevice.Viewport;

// ===================================================
// If you want to use the mouse, use this code
MouseState state = Mouse.GetState();
Vector2 screenPos = new Vector2(state.X, state.Y);
// ===================================================

// ===================================================
// If you want to use a reticule centered at the middle of the screen, use this code
Vector2 screenPos = new Vector2(viewPort.X + Math.Floor(viewPort.Width * 0.5f),
                                viewPort.Y + Math.Floor(viewPort.Height * 0.5f))
// ===================================================

// Create two positions in screenspace using the cursor position. 0 is as
// close as possible to the camera, 1 is as far away as possible.
Vector3 nearSource = new Vector3(screenPos, 0f);
Vector3 farSource = new Vector3(screenPos, 1f);

Vector3 start = viewPort.Unproject(nearSource, projectionMatrix, viewMatrix, Matrix.Identity);
Vector3 end = viewPort.Unproject(farSource, projectionMatrix, viewMatrix, Matrix.Identity);

```

This gives you a line segment with which to check boxes against, and it should work with any XNA-based game. And if you planned things well then your boxes are exactly 1x1x1, which makes it very easy to know which block areas the line goes through. You would write an algorithm to check each of those areas, in order from nearest to the camera, to furthest, and as soon as a block is found then you're done.

One optimization you should make would be to shorten the line segment to only be as long as you want players to be able to click on blocks.

`Vector3 shortenedEndPoint = start + ((end - start).Normalize() * 20.0f)`

The above code would take the endpoints we calculated earlier and give you a new endpoint that is only 20 units away from the camera. By shortening it the amount of block areas you may have to check becomes much smaller.

Now, for an algorithm to find the blocks that the line segment collides with:

```
Block FindNearestBlock(Vector3 start, Vector3 shortenedEndPoint)
{
    int lowestX = Math.Floor(start.X);
    int highestX = Math.Ceiling(shortenedEndPoint.X);

    int lowestY = Math.Floor(start.Y);
    int highestY = Math.Ceiling(shortenedEndPoint.Y);

    int lowestZ = Math.Floor(start.Z);
    int highestZ = Math.Ceiling(shortenedEndPoint.Z);

    // Loop through all units we pass along the shortened line segment
    for ( int x = lowestX; x < highestX; ++x )
    {
        for ( int y = lowestY; y < highestY; ++y )
        {
            for ( int z = lowestZ; z < highestZ; ++z )
            {
                // Here you check if a block inhabits the area defined by
                // this point in space. This point represents the axis-aligned
                // block's minimum corner¹
                Vector3 minimumBoxCorner = new Vector(x, y, z);

                Block minCornerBlock = GetBlockAtMinimumCorner( minimumBoxCorner );
                if ( null != minCornerBlock
                {
                    return minCornerBlock;
                }
            }
        }
    }

    // If we made it here then there were no blocks in range that are in front
    // of the reticule.
    return null;
}

```

¹ **Minimum corner**: Refers to the corner of the box with the lowest X, Y, and Z values.

Please note, I created this algorithm off the top of my head, it may not even compile exactly as written, but hopefully you'll get the gist. An algorithm like this checks one block at a time, rather than moving in segments that could step over the edges of blocks.

EDIT: Just realized how similar my algorithm ended up being to Blecki's answer. Maybe that gives some merit to each answer as being a good possible solution, seeing as how we both came to similar conclusions.

# Answer
> 1 votes
The operation you want is ray-voxel intersection. You want to step through all the grid cells that the ray intersects, in order of their distance, and stop when you find a non-empty one. A lovely algorithm for this can be found in this easily digestible paper. It is similar to Bresenham's algorithm.

This algorithm gives you an intersecting cell every time through the loop, so the running time is linear with the distance to the target voxel. Some of the other algorithms presented here run in cubic time, which seems very wasteful.

---
Tags: xna, c#, minecraft-modding, voxels
---