title: How to swap row/column major order?

text:
# Question
Title: How to swap row/column major order?
I'm trying to get a sprite sheet clipped in the right order but I'm a bit stumped, every iteration I've tried has tended to be in the wrong order. This is my current implementation.

```
    Frames = (TempSurface->h / ClipHeight) * (TempSurface->w / ClipWidth);
    SDL_Rect Clips[Frames];
    for (i = 0; i < Frames; i++) {
            if (i != 0 && i % (TempSurface->h / ClipHeight) == 0)
                    ColumnIndex++;
            Clips[i].x = ColumnIndex * ClipWidth;
            Clips[i].y = i % (TempSurface->h / ClipHeight) * ClipHeight;
            Clips[i].w = ClipWidth;
            Clips[i].h = ClipHeight;
    }

```

Where `TempSurface` is the entire sheet loaded to a `SDL_Surface` and `Clips[]` is an array of `SDL_Rects`. What results from this is a sprite sheet set to `SDL_Rects` in the wrong order.

For example I need a sheet of dimensions 4x4 to look like this:

```
| 0 | 1 | 2 | 3 |
| 4 | 5 | 6 | 7 |
| 8 | 9 | 10| 11|
| 12| 13| 14| 15|

```

But instead I get this order:

```
| 0 | 4 | 8 | 12|
| 1 | 5 | 9 | 13|
| 2 | 6 | 10| 14|
| 3 | 7 | 11| 15|

```

Columns and rows order does not match. What should I do to fix the order?

# Answer
> 4 votes
You just swap your rows/columns ordering. Iterating from `0` to `Frames-1`, you first increase `X` and every time you hit the spritesheets width - increase `Y` and reset `X`.

The code should be looking like so:

```
for (i = 0; i < Frames; i++) {
    // Increase the row once every time horizontal range is done
    if (i != 0 && i % (TempSurface->w / ClipWidth) == 0)
        RowIndex++;

    Clips[i].x = i % (TempSurface->w / ClipWidth) * ClipWidth;
    Clips[i].y = RowIndex * ClipHeight;
    Clips[i].w = ClipWidth;
    Clips[i].h = ClipHeight;
}

```

---
Tags: c++, spritesheet
---


# Question
Title: MonoGame not all letters being drawn with DrawString
I'm currently making a dynamic user interface for my game and are setting up having text on my buttons. I'm having an odd issue where, when i use a specific piece of code to determine the text position, it will not render all of the text passed to `DrawString`. Even weirder, is if i insert another `DrawString` after this, drawing more text at a different place, different parts of the text will be drawn.

The code for drawing my button with the text attached is:

```
public override void Draw(SpriteBatch sb, GameTime gt)
{
    sb.Draw(currentImage, GetRelativeRectangle(), Color.White);
    sb.DrawString(font, text,
        new Vector2(this.GetRelativeDrawOffset().X + this.Width / 2 - font.MeasureString(text).X / 2,
            this.GetRelativeDrawOffset().Y + this.Height / 2 - font.MeasureString(text).Y / 2), textColor);
}

```

The methods in the creation of the `Vector2` simply get the draw position of the button. I'm then doing some calculation to center the text.

This produces this when the text is set to 'Test':

And when i enter this piece of code below the first `DrawString`:

```
sb.DrawString(font, "test", new Vector2(500, 50), Color.Pink);

```

I should mention that that grey square is being drawn in the same `spritebatch`, before the button and the text.

Any ideas as to what could be causing this? I have a feeling it may be due to draw order, but i have no idea how to control that.

# Answer
> 1 votes
This is probably because `SpriteBatch` is doing some layer ordering behind the scenes that is not likely what you want. You have three ways to fix this, choose what fits you best:

* Separate this rect and the text batches.

Example:

```
batch.begin(/*...*/);
batch.draw(/*rectangle*/);
batch.end();
batch.begin(/*...*/);
batch.drawString(/*text*/);
batch.end();

```
* Use the `layerDepth` argument to organize it. This should be the preferred method, since you can combine rendering any way you want to organize things.

Example:

```
batch.begin(/*...*/);
batch.draw(/*rectangle*/, 1.0f); //1 is the backlayer
batch.drawString(/*text*/, 0.0f); //0 is the front layer
batch.end();

```

You can make windows sit at 1.0f, buttons at 0.9f, button outlines at 0.85f, text at 0.7f... any combination should work.

* On `spriteBatch.begin()`, set the SpriteSortMode to BackToFront or Texture. Everything should be drawn in the order you call the draws.

---
Tags: xna, c#, graphics, monogame
---


# Question
Title: Make the player run onto stairs smoothly
I have a 2D Platform game, where the player Always runs to the right, but the terrain isn't Always horizontal. Example:

I implemented a bounding-box collision system that just checks for intersections with player box and the other blocks, to stop player from running if you encounter a big block, so that you have to jump, but when I put stairs, I want him to run smoothly just like he is on the horizontal ground. With the collision system you have to jump the stairs in order to pass them!

I thought about generating a line between the edges of the stairs, and imposing the player movement on that line... What do you think? Is there something more clever to do?

# Answer
If you're able to rotate the boundingboxes, I would've put a 45 degree rotated box at the player's feet and combine it with one non-rotated box to represent the rest of the body. That could make the player automatically slide over anything small enough.

Though, that would probably cause some clipping with the player model and the stairs.

Another idea is to put one boundingboxes from the character's head to kness with higher width than the box of the character.

When the player collides with something which the box 'A' does not, you can move the player ontop of what it collided with

```
_________________
|    |     |    |
|    |     |    |
|  A | pla | A  |
|____| yer |____|
     |     | _________________________ <- step
     |     | |
--------------------------------------------- <- ground

```
> 10 votes

# Answer
There are three general approaches to dealing with stairs in video games:

The "Mario" approach is that you must jump to get up stairs.

The "Castlevania" approach is that moving up/down stairs is a different sort of movement; you must press 'up' on the controller, and a special "stair-climbing" animation is played to traverse the stairs. A variant of this is the "Resident Evil" approach, where moving up/down stairs is treated as a complete cutscene that plays when the player presses an interaction button; no interactive stair-climbing is permitted whatsoever.

The "Almost Everyone Else" approach is the one that you mentioned: treat the stairs as if they were actually a ramp. Depending on what sort of game it is, you may wish to place the ramp at different heights relative to the stairs. Typically in a 2D game, the "the stairs are actually a ramp" trick is less noticeable to the player if the ramp is level with the bottom corners of each stair step, while in a 3D game it's typically less noticeable if the ramp is level with the top corners of each step. (as in a 2D game it's easier to notice if a character's feet are floating above the ground, and so you want to minimise that, whereas in a 3D game it's easier to notice if a character's feet are clipping through the ground, and so you want to minimise that).
> 11 votes

# Answer
Most of the methods I've encountered have already been stated above -- but there's still one more that hasn't been mentioned. When the player encounters a vertical obstacle that's short enough (say, 1/3 their hight), simply put them on the top. Minecraft and the Source engine for example take this approach in that kind of situation. Additionally, this method allows you to still use pure AABB for all of the physics while not putting the player through the pain of constantly having to jump up stairs.
> 3 votes

# Answer
I'm currently working on a similar part of an engine, and the way I dealt with stairs/slopes is by counting the transparent pixels in my ramp texture and offsetting the player's object by the amount found.

It is similar to the idea of the height map that is detailed in this article: http://info.sonicretro.org/SPG:Solid\_Tiles#Slopes\_And\_Curves

I imagine that's really what you would be looking to do, and you can choose to play a different animation that plays according to the ascension of the stairs.

There is also a good overview of the different slope concepts in this article: http://higherorderfun.com/blog/2012/05/20/the-guide-to-implementing-2d-platformers/
> 0 votes

---
Tags: xna, collision-detection, xna-4.0, collision-resolution, platformer
---


title: Inversion of control in Unity?

text:
# Question
Title: Inversion of control in Unity?
I am semi-experienced .NET developer who has just began working with Unity. I am trying to decide on how to make IoC work in Unity 4.X ( I have not yet tested anything), and I wonder what are the good ways of achieving it.

This post and its answers states that Ninject won't work with Unity, however it is old. Is it still true? If yes, what are other means of achieving IoC in Unity ?

Edit 1 : I am targeting mainly Windows platform. So I don't need platform interoperability, I just need it to work.

# Answer
You probably want to look at StrangeIOC.

http://strangeioc.github.io/strangeioc/

It's meant for Unity. The project has been under active development for quite some time, and I keep meaning to check it out, but as of yet I haven't so I can't give you the personal recommendation. But it sounds like exactly like what you want.
> 5 votes

# Answer
I don't know, but nobody did managed to run it under unity: http://forum.unity3d.com/threads/ios-dependency-injection-framework-suggestions.119909/ but can be very outdated. Nonetheless, try to post your question to UnityAnswers, where will you get more likely a proper answer.
> 0 votes

---
Tags: unity, dependency-injection
---


# Question
Title: What libgdx project files can I ignore from version control?
In an automatically created libgdx project, what files can I safely tell Git (or other revision control systems) to ignore?

I'm considering these:

```
*-android/.settings/
*-android/bin/
*-desktop/.settings/
*-desktop/bin/
*-html/.settings/
*-html/gwt-unitCache/
*-html/war/WEB-INF/classes/
*-html/war/WEB-INF/deploy/
*-html/war/assets/
*-html/war/
*/.settings/
*/bin/

```

Am I missing some? Is there a complete list somewhere?

# Answer
Ignore all the `/bin/` directories (they contain files generated from sources). The `/war/` directory hierarchy is similar (generated files for the GWT/HTML backend).

You can ignore the `/.settings/` directories, as they contain Eclipse settings, and are not required to be able to re-build your application. (These are probably a bad idea to push into git if you expect to work with other developers, as they tend to have local paths in them.)

On the Android side, you should also leave out the `gen` directory

For the Eclipse `.project` and `.classpath` files see https://stackoverflow.com/questions/2818239/classpath-and-project-check-into-version-control-or-not (the answer there seems to be "yes, include them if using at least Eclipse v3.5").
> 12 votes

# Answer
The new project generator comes with autogenerated .gitignore file like:

```
## Java

*.class
*.war
*.ear
hs_err_pid*

## GWT
war/
html/war/gwt_bree/
html/gwt-unitCache/
.apt_generated/
html/war/WEB-INF/deploy/
html/war/WEB-INF/classes/
.gwt/
gwt-unitCache/
www-test/
.gwt-tmp/

## Android Studio and Intellij and Android in general
android/libs/armeabi/
android/libs/armeabi-v7a/
android/libs/x86/
android/gen/
.idea/
*.ipr
*.iws
*.iml
out/
com_crashlytics_export_strings.xml

## Eclipse
.classpath
.project
.metadata
**/bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.externalToolBuilders/
*.launch

## NetBeans
**/nbproject/private/
build/
nbbuild/
dist/
nbdist/
nbactions.xml
nb-configuration.xml

## Gradle

.gradle
build/

```
> 11 votes

# Answer
You can have separate .gitignore files for each folder. So you can put a specific Android .gitignore on the Android project and so on. Without worrying about libgdx in general.

Github has good pre-made templates for Android and GWT (which libgdx uses for the web version). You could just use those and place each on their specific directory.

List of templates: https://github.com/github/gitignore
> 2 votes

---
Tags: libgdx, version-control
---


# Question
Title: How to store an iOS game save file in multiple devices? (Without remote servers)
I've been developing an iOS game for iPhone. My game saves the progress as a couple of .plist documents in the device.

I have come to realize that when I install a game in my iPhone, this same game is installed in my iPad. And then it struck me: how would I manage save files? I mean, I'd like the player to be able to continue playing from where they left no matter what device are they using... without using remote servers.

What have you done to address this issue?

# Answer
I don't think this would be possible over the internet. Having mobile devices connect to each other, without an intermediate server is near impossible. Since one or the other would have to broadcast its location in someway that the other could respond to. I'm not familiar with a way to do that if the devices don't already know about each other.

However, on a much smaller network, like a home wifi network. This is reasonable. Both devices would need to be connected to the same wifi network. From there they can communicate and sync save files.
> 4 votes

# Answer
I would say try using iCloud. But technically, it is a remote server. At least you do not need to handle anything on the server side.
> 2 votes

# Answer
You can check Game center, there are two systems that I know which can help you:

1. GameKit provides interfaces to transfer data over the Bluetooth, I'm not sure about the specifications but it's possible! here is an example: iPhone Bluetooth Programming
2. GameKit also offers support for Turned based games over the internet, If I'm not wrong you can use this feature to sync player profile on both devices. GKTurnBasedMatch Class Reference

There might be other options available too also you might want to take a look at both OpenFeint and GameKit for similar or better solutions.
> 1 votes

# Answer
Perhaps you can do it via email? Have your game communicate with SMTP/IMAP, let your user log in with an email address, then send your save game data. The other device would then check for the particular mail with the save game then store it.

You'd need to be connected to the Internet though.

Since your game is mobile, Gajoo's suggestion about Bluetooth sounds best.
> 0 votes

---
Tags: ios
---


# Question
Title: Can I use copyrighted images and music in my game?
I am working on my first ever project , and I have used some copyrighted images(images taken from some other well recognized games). Is it even possible that I edit the images a little bit and then use them as royalty free images?

# Answer
The best thing to do here is to create something new "in the spirit of" the thing you're borrowing from. ***Do not*** copy graphics and just edit them in photoshop. You'd have to change them **A LOT** before it would be without legal risk. And it's also low rent. Be better than that.

Let me give you an example by looking at music for a second. If you pay attention you will see (hear) that tv shows will often use songs that sound similar to another song. I used to be an editor on reality tv shows. We had an arsenal of original music that was supplied to us by the producers. And the guy that created all that original music would often borrow heavily, or almost even parody, another song. If they need a spy theme he would make them a James Bond sounding thing with some of the notes changed. But you could definitely tell that it was supposed to sound like James Bond.

But here's the difference. He ***did not*** go in to a sound program, use the original recording and change the notes around. He completely re-recorded a ***new song*** that had a similar vibe and maybe shared some of the same notes. He might have listened to the original song, played it just like the original, and then figured out notes to change. But it was now original. Music is tricky because the rights for the tune (notes) and the arrangement or recording are two different things. It's best to get original music and a liberal license agreement.

For graphics. I once did a game where I needed graphics that looked like an old tin toy robot. I brought the robot graphics in to photoshop and then ***drew*** new graphics that looked very similar to what I was borrowing from. But in the end it was a completely new graphic. Wheels and pullies and gears of the robot were all in different places and different sizes. I didn't even trace it. But having them side by side helped me design something new in the spirit of the thing I was paying homage to. And if I get sued or get a take down notice, I have my source layered photoshop document that I can pull out and prove that I created it from scratch.

There are of course stock sites where you can get music and graphics. But even on those ***read the license*** and make sure that your usage falls within that allowed license. Very often on music sites the license they're selling you does not include usage in a game. I've seen stock graphics where the license was limited on the number of end users can get it. Look for "royalty free" licenses.

I often hire people to create graphics and it doesn't have to be expensive. $100 or even free sometimes.

My next game is going to have a really cool metal song for the main title. A friend has a band and he wanted to record something for me for free. Even then we'll sign a license agreement.
> 2 votes

# Answer
You can, but you'll need permission from the original copyright owner - there's no way around it, unless there's some license attached allowing you to do that specifically.

It doesn't matter whether you modify or edit the images (or any other copyrighted work).

Some legislations got special rules for such, e.g. it's possible that something is so obvious or simple that noone can claim any rights on it (for example a simple red dot without anything else).

But as with most legal questions, ask a lawyer. Some might even agree on helping you with simple/basic questions for free. Don't trust random internet people, because they might as well be the ones just waiting to sue you seconds later. ;)
> 4 votes

# Answer
No, **of course** you can't take somebody else's work, modify it "a little bit" and then release it as your own.

That you would even ask the question indicates that you're dangerously unaware of international intellectual property laws. You really need to bring yourself up to date on the very, very basics of Copyright and Trademark law (like, what they are, what they cover, and when they don't apply), before you accidentally do something that gets you into trouble and potentially fined or jailed for violating someone else's rights to their creations.
> 0 votes

---
Tags: image, copyright
---


title: Saving game data to server

text:
# Question
Title: Saving game data to server
What's the best method to save the player's data to the server?

**Method to store the game saves**
Which one of the following method should I use ?

* Using a database structure(e.g.. mySQL) to store the game data as blobs?
* Using the server hard disk to store the saved game data as binary data files?

**Method to send saved game data to server**
What method should I use ?

* socketIO
* web socket
* a web-based scripting language to receive the game data as binary? for example, a php script to handle binary data and save it to file

**Meta-data**
I read that some games store saved game meta-data in database structures. What kind of meta data is useful to store?

**Edit-1**
This question was to actually see what technology is better to use based on the situation. The situation is a game that will be on cross-platform, save game throughout the cloud.

Method of delivery from game client(iOS, Android, Windows Phone 8, etc..) to game server(Linux, Windows, etc.) Im using a Ubuntu server at this moment.

Method of storage of binary data Inside a database system or file system. The up and down side to it and the community options of existing structures.

Storing of meta-data Well, I'm not too sure about how to store saved game data to server at the moment. Thus, was wondering if the community can provides tried and tested methods used by the community. and their preferences.

# Answer
> 1 votes
There are many questions here - I'll try to answer each of them. Entire books have been written to address these, but I'll try to be brief.

> what's the best method to save player's game binary save data to the server?

HTTP Post to custom server handler to persistent(DB) store.

> Method to store the save game

Anything - could be MySQL, PostgreSQL, Mongo, Flat File, or whatever you want. You really have to look at the strengths and weaknesses are for each and determine which one is best suited for your game.

Given that you are new to this, I would recommend something more along the lines of Mongo or Couch DB. They store the information you send to them as a document without any hardcoded schema(which has it's drawbacks, but that is for another article).

> Method to send saved game data to server

Depends on your game really. If you need second to second real-time saves, then you could use websockets, or if you only need save games every once in a while then you could use just regular http post data to a server.

Be careful though as websockets constantly updating databases can get very expensive, so try to balance how frequently you need to update with the actual cost of running the service. Load test and profile!

> What kind of meta data is useful to store?

Everything! Storage is cheap, so don't be shy(but also don't waste too much of it otherwise you're just being greedy). If you think about it for a minute, ask yourself what kind of information you would want out of your data. How long the user plays the game? What the average game-play session is? Then think about what you need to store from those basic questions. Start/end-time are obvious, but what about system hardware specs so you know what kind of hardware your users are playing on? What about geolocation information coupled with average session length to give you a better idea where to target your advertising? These are all things that can be done, but you will have to figure out what you want to store and how you are going to store it.

---
Tags: server, savegame
---


# Question
Title: How does this circle collision detection math work?
I'm going through the wildbunny blog to learn about collision detection. I'm confused about how the vectors he's talking about come into play.

Here's the part that confuses me:

> p = ||A-B|| – (r1+r2)
>
> The two spheres are penetrating by distance p. We would also like the penetration vector so that we can correct the penetration once we discover it. This is the vector that moves both circles to the point where they just touch, correcting the penetration. Importantly it is not only just a vector that does this, it is the only vector which corrects the penetration by moving the minimum amount. This is important because we only want to correct the error, not introduce more by moving too much when we correct, or too little.
>
> N = (A-B) / ||A-B||
>
> P = N\*p
>
> Here we have calculated the normalised vector N between the two centres and the penetration vector P by multiplying our unit direction by the penetration distance.

I understand that *p* is the distance by which the circles penetrate, but I don't get what exactly *N* and *P* are. It seems to me *N* is just the coordinates of the 3rd point of the right trianlge formed by point A and B **(A-B)** then being divided by the hypotenuse of that triangle or distance between A and B **(||A-B||)**. What's the significance of this?

Also, what is the penetration vector used for? It seems to me like a movement that one of the circles would perform to get un-penetrated.

# Answer
> 3 votes
I assume that *A* and *B* are the centers of the two spheres: Sa, Sb.

*V* = *A* \- *B* is the vector that moves the center of Sa to the center of Sb: you see that *A* \+ *V* = *B*.

||*A* \- *B*|| is the magnitude of *V* or modulus or length - as you prefere - that is the distance between the two spheres' centers: p tells you how much the spheres are "too close" to each other.

*N* = *V* / ||*A* \- *B*|| is a unit vector (length = 1) that shares the same direction of *V* so P = *N*·p si a vector that has the same direction of *V* and the length of p.

You don't want to move Sa toward Sb a little more so you will add *P* to *B* moving Sb far way from Sa in the right direction (*N*) and for the correct amount (p).

# Answer
> 3 votes
I will assume that A and B are the centers of the respective circles.

First, we have two circles that move by some given velocities. When you update the position of the circles at the beginning of a new frame, their position will change by `Velocity * diff`, where diff is the time passed from last frame. If the collision engine finds that these two circles are now penetrating each other, then it must move one or both of them so that they will not be still penetrating. The most realistic way of doing this is by trying to minimize diff so it will find the exact moment when the two circles collide and then stop them here, but that's irrelevant because that's not how the article you're reading does. It assumes it is good enough to move them by the minimum distance possible for them to not be still penetrating.

Let's say you want to move circle 1 in case of penetration. You know the penetration (you calculate it by `p = ||A-B|| – (r1+r2)`) and that's the distance you will move your circle across for them to be just in touching contact (remember you want to move it by as little as possible and that's p), so you must find the direction along which you need to move the first circle.

Look at the image and you will see that N (the direction vector) is exactly `A - B`. It must be normalized before multiplying with p (a normalized vector multiplied by a value will have a magnitude equal to that value, e.g. moving circle 1 p distance along N). `N = (A-B) / ||A-B||` gives us that direction and `P = N*p` gives us the penetration vector, which must be added to the position of circle 1 so they will be just in touching contact. P is exactly the line I highlighted in green.

Hope it helps. Let me know if I was unclear.

EDIT: I haven't seen the date of this question when I answered it, so I don't think the OP still needs an answer. Hope it helps other people.

# Answer
> 0 votes
The text is a bit unclear, using the word normal incorrectly. N is the normalised vector pointing from B to A, meaning it has the same direction as B to A but length 1.

What are you trying to do by the way? The blog talks a lot of collision detection, but seemingly nothing about collision resolution, which depend on what kind of physics you'd like.

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


# Question
Title: From where does the game engines add location of an object?
I have started making my first game( a pong game )with ruby (Gosu). I'm trying to detect the collision of two images using their location by comparing the location of the object (a ball) to another one(a player).

For example:

```
if  (@player.x - @ball.x).abs <=184 && (@player.y - @ball.y).abs <= 40
            @ball.vx = -@ball.vx
            @ball.vy = -@ball.vy

```

But my problem is that with these numbers, the ball collides near the player sometimes, even though the dimensions of the player are correct.

So my question is from where does the x values start to count? Is it from the center of gravity of the image or from the beginning of the image? (i.e When you add the image on a specific x,y,z what are these values compared to the image?

# Answer
The origin is in the top left corner.

* The x, y coordinate are from the top left corner of the screen to the top left corner of your image.
x: horizontal and y: vertical.
* The z coordinate changes the order of display, the images with a higher z position will be drawn over those with a lower one (source)
> 1 votes

---
Tags: collision-detection, ruby
---


# Question
Title: How to solve problems with movement in simple tile based multiplayer game?
I'm making a simple tile based 2D multiplayer game in JavaScript using socket.io where you can move one tile every 200 ms. The two solutions I've tried are as follows:

* The client sends "walk one tile north" every 200 ms. Problem: People can easily hack the client to send the action more often.
* The client sends "walking north" and "stopped walking". Problem: Sometimes the player moves extra steps when "stopped walking" doesn't arrive in time.

Do you know a way around these problems or is there a better way to do it?

**EDIT:** Regarding the first solution I've tried adding validation on the server to check if it has been 200 ms since last movement. The problem is that latency still encourages people just to spam the action as much as possible, giving them an unfair advantage.

# Answer
> 0 votes
Both options are viable.

The "walk north every 200ms" can be fixed server-sided by queueing the commands of each client on the server. When the server receives "up, up, left, up, up" from one client in fast sequence, the server pushes these five move-actions on a queue and processes one input every 200ms.

The "stop walking" can be synchronizing by making the stop-position a part of the stop-message. Be careful, though: A client might attempt to manipulate the stop-location to gain an advantage. Sending move messages with stop-locations much further than the distance the client could have traveled in that time could allow speed-hacking. A heuristic approach could be used to detect this: keep a log of player positions and kick those which regularly exceed the maximum possible velocity.

---
Tags: 2d, javascript, multiplayer, client-server, websocket
---


title: #iterator() cannot be used nested

text:
# Question
Title: #iterator() cannot be used nested
I'm getting this error when I try to check if any of the targets overlap each other:

```
iterTargets = targets.iterator();
while (iterTargets.hasNext()) {
    Target target = iterTargets.next();

    for (Target otherTarget:targets) {
        if (target.rectangle.overlaps(otherTarget.rectangle)) {
            // do something
        }
    }
}

```

So I can't do that? How am I supposed to check each member of an array to see if it overlaps any other member?

# Answer
Try the following piece of code:

```
for(int i = 0; i < objects.size() - 1; ++i)
    for(int j = i + 1; j < objects.size(); ++j)
        //compare obj[i] and obj[j] - check collision here

```
> 1 votes

---
Tags: collision-detection, libgdx
---


# Question
Title: How do I prevent other dynamic bodies from affecting the player's velocity with Box2D?
I'm working on my player object for my game.

```
PhysicsBodyDef def;
def.fixedRotation = true;
def.density = 1.0f;
def.position = Vec2(200.0f, 200.0f);
def.isDynamic = true;
def.size = Vec2(50.0f,200.0f);

m_player.init(def,&m_physicsEngine.getWorld());

```

This is how he moves:

```
b2Vec2 vel = getBody()->GetLinearVelocity();
float desiredVel = 0;

if (m_keys[ALLEGRO_KEY_A] || m_keys[ALLEGRO_KEY_LEFT])
{
    desiredVel = -5;
}
else if (m_keys[ALLEGRO_KEY_D] || m_keys[ALLEGRO_KEY_RIGHT])
{
    desiredVel = 5;
}
else
{
    desiredVel = 0;
}

float velChange = desiredVel - vel.x;
float impulse = getBody()->GetMass() * velChange; //disregard time factor
getBody()->ApplyLinearImpulse( b2Vec2(impulse,0), getBody()->GetWorldCenter(),true);

```

This creates a few problems. First, to move the player at a constant speed he must be given a high velocity. The problem with this is if he just comes in contact with a small box, he makes it move a lot.

Now, I can fix this by lowering his density, but then comes my main issue: I need other objects to be able to run into him, but when they do, he should be like a static wall and not move.

I'm not sure how to do that without high density. I cannot use collision groups since I still need him to be solid toward other dynamic things.

How can this be done? Essentially, how do I prevent other dynamic bodies from affecting the player's velocity?

# Answer
First

If you don't want the "small box" to move a lot just increase it's density a lot. Why not do that?

Other than the obvious:

If I recall correctly, you can detect collisions in Box2d (i.e. set a callback) and there return false to not have the collision handled by the physics system. I think you could have it so when certain things collide with the player, the player does not move at all while when other things collide with her, the behavior is different.
> 2 votes

# Answer
Have 2 bodies for your player, one that is dynamic and one that is kinematic, connected by a weld joint. Use collision groups so these two bodies do not collide with each other. Also use the collision groups so that the kinematic body only interacts with things that shouldn't influence the players movement, and use the dynamic body for ones that should.
> 2 votes

# Answer
Short answer: you can't. Not as long as the player is represented by a dynamic physics body.

You should rather make the player a kinematic body and directly set the player's velocity every time before stepping the physics world - this is essentially the same what applying impulse does, but you have more control over the actual velocity if you do set velocity manually. For example you no longer need to factor in mass/density in the equation, which should make your body move on a "points per frame" basis and not require a high impulse force.
> 1 votes

---
Tags: c++, physics, box2d
---


# Question
Title: Convert vector interpolation to quaternion interpolation? (Catmull-Rom)
I have some existing code which does catmull-rom interpolation on two vectors (facing and up). I'm converting this to use quaternions instead (to replace the two vectors). Is there a general way to convert the vector based interpolation to a quaternion one?

The approach I'm using now is to exact the axis and angle from the quanternion. I then interpolate each of those independently and convert back to a quaternion. Is there a more direct method?

# Answer
> 4 votes
Since it seems acceptable, I’ll go for the following suggestion: just interpolate the quaternion components, then normalise the resulting quaternion.

* *pro*: it’s fast and the code is short
* *pro*: and there is no need to handle the case when the angle reaches 360 degrees and warps back to zero.
* *con*: you can still get singularities if the quaternions aren’t carefully computed
* *con*: the derivative of the rotation angle is not constant along the curve (but it’s still *almost* constant)

If that last issue becomes problematic, you could use slerp() instead of linear interpolation. Slerp only works with two quaternions whereas in a Catmull-Rom spline you usually blend four, but there is a method (see Barry and Goldman's pyramidal formulation) that lets you compute the spline using only pairwise interpolations if you attach time values to each point.

# Answer
> 2 votes
In one of the earlier Game Programming Gems books there exists an article which outlines how to do spline interpolation of orientations represented with quaternions.

The gist is that a mapping from SO(3) to R4 is made, the interpolation is performed component-wise in R4 as with any other vector, and a reverse mapping from R4 to SO(3) is performed.

I believe that the mapping should be largely free of singularities, but you would have to consult the text to find out the particulars.

```
inline float4 SO3ToR4(Quat const& q)
{
    float const mul = 1.0f / sqrt(2.0f * (1.0f - q.w));
    return float4(q.x, q.y, q.z, (1.0f - q.w)).Mul(mul);
}

inline Quat R4ToSO3(float4 const& v)
{
    float4 const sq = v.Mul(v);
    float const denom = v.SumOfElements();
    float const s = sq.xyz().SumOfElements() - sq.w;
    return Quat(
        2.0f*v.x*v.w/denom,
        2.0f*v.y*v.w/denom,
        2.0f*v.z*v.w/denom,
        s/denom);
}

```

---
Tags: mathematics, quaternion, interpolation
---


# Question
Title: Open GL perspective projection vs orthographic projection
I am trying to build an engine using OpenGL however I have a question about the kind of projection to use.

1. For a 2D game should I use a perspective projection or an orthographic projection?
2. If I wanted to have the ability to use 3d in a 2d oriented game, which one should I use?

# Answer
Using orthographic projection means everything will be projected to a 2D plane and objects will not be affected by the distance and/or angle from which you see them. Look at the image and you'll understand:

The two objects are exactly the same, but they are projected differently. Notice how distance affects what you see if you're using perspective projection. That gives the 3D touch to the engine. You don't need that in a 2D game.

If you don't want to include 3D in your engine you should be using an orthographic projection and an eye point (the point from which you are looking at the environment) above the ground.
> 7 votes

---
Tags: opengl, c++
---


# Question
Title: Polygons vs sprites rendering performance in Unity for windows phone 8
I'm currently building a windows phone 8 game with unity, having 111 (no more no less) sprites being updated each frames. I have a strong overhead in the profiler (70% to 90% minimum) I tried the following to get higher frame rate,

* I'm running it with minimum quality settings,
* I tried disabling and enabling V-Sync

Finally I managedto get 60Fps, but I still have large overhead. I believe I should have more than 60Fps for such few amount. Moreover, I still have to implement the game logic over this so I'd like some room in my FPS to be able to work.

I was wondering if it would be better in terms of performance to use polygons instead of sprites? As sprites are quite new in Unity, (that would give me around 222 triangles).

Did someone tried to check the performance differences between sprites and actual mesh renderes in Unity when it comes to phones? If so what could be the best option in that case?

FYI : I'm using the Windows Phone 8 emulator on Visual studio, I have a compliant computer for that so it should normally reflect the behavior of a real phone (expecting some differences but still...)

EDIT : To clarify my question i wonder what is the most efficient in windows phone 8 : Sprites or Mesh renderers?

# Answer
> 2 votes
Looks to me that you are falling into the frame per second measurement trap; instead you should use seconds per frame (frame time) and see how much frame time changes.

Frames per second are non-linear and they don't provide an accurate performance measurement, *they are deceiving*. For example if adding a 3DModel/Sprite to your application is causing 900FPS to 450fps drop, while using an alternative model caused a drop from 60FPS to 55FPS the latter's impact could be much more sever in other words the frame time is being affected more, so in order to get an accurate measurement calculate how much the frame time is being affected and not the FPS.

Moreover, *sprites are polygons*, if you are going to implement your own sprites version using polygons; this is sth the engine is already doing, and the engine is probably doing some optimizations for state changes, something you may not have access to.

P.S. Test on the actual device rather than the emulator, the emulators performance can also be much different.

P.P.S BTW you are saying you are having 70%-90% for the sprites rendering in the profiler. This is expected since this is the only major thing implemeted in your game, so it makes sense to take the most percentage.

# Answer
> 0 votes
Actually for that particular case for future reference i want to add as answer that restarting my computer did gave me 60FPS after reboot on the emulator, without changing anything, with more optimization it could go even faster.

@concept3d answer is still the valid one though and the article about why FPS is an incomplete indicator is a perfect reference

# Answer
> 0 votes
You're using profiler on your computer instead of profiling on the actual device. That's why you're getting this big overhead.

Also you're saying that you're using phone emulator which is reflecting the phone's behavior. You're wrong. Emulators will *never* give you the same stats as a real device and you should not rely on the FPS you're getting on an emulator. It can be completely different and misleading.

---
Tags: unity, sprites, performance, windows-phone-8
---


# Question
Title: Deslect targeted enemy question. How to change back to original color
In the code below I have now:

* Press tab, enemy changes green.
* Press tab again, (deselecting the target) **enemy changes to blue**.

What I want to happen:

* Press tab, enemy changes to green.
* Press tab again, (deselecting the target) **green goes away**. (enemy is its **original color**)

Here is my current code:

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Targetting : MonoBehaviour {
    public List<Transform> targets;
    public Transform selectedTarget;

    private Transform myTransform;

    // Use this for initialization
    void Start () {
        targets = new List<Transform>();
        selectedTarget = null;
        myTransform = transform;

        AddAllEnemies();
    }

    public void AddAllEnemies()
    {
        GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");

        foreach(GameObject enemy in go)
            AddTarget(enemy.transform);
    }

    public void AddTarget(Transform enemy)
    {
        targets.Add(enemy);
    }

    private void SortTargetsByDistance()
    {
        targets.Sort(delegate(Transform t1,Transform t2) {
                return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));
                });
    }

    private void TargetEnemy()
    {
        if(selectedTarget == null)
        {
            SortTargetsByDistance();
            selectedTarget = targets[0];
        }
        else
        {
            int index = targets.IndexOf(selectedTarget);

            if(index < targets.Count -1)
            {
                index++;
            }
            else
            {
                index = 0;
            }
            DeselectTarget();
            selectedTarget = targets[index];
        }
        SelectTarget();
    }

    private void SelectTarget()
    {
        selectedTarget.renderer.material.color = Color.green;
    }

    private void DeselectTarget()
    {
        selectedTarget.renderer.material.color = Color.blue;
        selectedTarget = null;
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Tab))
        {
            TargetEnemy();
        }
    }

}

```

# Answer
> 0 votes
In your `SelectTarget` method, try changing

`selectedTarget.GetComponent().color = Color.red;`

to

`selectedTarget.renderer.material.color = Color.red;`

Same for your `DeselectTarget` method.

`selectedTarget.renderer.material.color = Color.blue;`

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


# Question
Title: what function creates rotation effect in three.js?
which part of the code is responsible for the rotation in this example? Is it the camera or the scene itself?

http://threejs.org/examples/#canvas\_camera\_orthographic

# Answer
> 2 votes
in the render function, you have

```
function render() {

    var timer = Date.now() * 0.0001;

    camera.position.x = Math.cos( timer ) * 200;
    camera.position.z = Math.sin( timer ) * 200;
    camera.lookAt( scene.position );

renderer.render( scene, camera );

}

```

That makes the camera take a circular path of radius 200 , always looking at the center of the scene

# Answer
> 1 votes
According to the source they call the render method and it simply updates the camera position and uses camera.lookAt() to calculate the matrix to look at the center.

---
Tags: javascript, camera, three.js
---


# Question
Title: Is there a 3D equivalent of hex tile maps?
Probably the biggest advantage of a hex-based versus square-based map tiling is that the center of each hex has the same distance to all its neighboring hexes. Is there a similar shape that tiles this way in 3D, and an engine that supports such a model?

# Answer
Google and Wikipedia tag team to the rescue:

Tessellation and, more specific for 3D, Honeycomb is the term to look for. Cubes are indeed the only regular (all faces are congruent) AND space-filling (no gaps left as with sphere packing) polyhedra in 3D space. But they have the same problem as 2D squares - widely varying distances to its neighbors.

A Bitruncated cubic honeycomb made of truncated octahedra (quite a mouthful) comes very close to what I was asking for. The downsides are that the truncated octahedron is not regular (squares and hexes as faces) and has fewer neighbors than a cube (14 vs 26), but it fills space with a single, repeated solid and has (roughly) equal distance to all its neighbors.
> 25 votes

# Answer
2D hexagonal maps are a representation of spheres packed in a flat (2D) tray, with each hex centred on the equivalent sphere, and allow distances between cells to be determined to workable (for gaming purposes anyway) accuracy, just by counting the number of hex cells through which you step.

The equivalent 3D representation is the face-centred cubic (FCC)/cubic close packing (CCP) tessalation mentioned above, using rhombic dodecahedra.

This Wikipedia article refers to FCC/CCP in particular and this other article compares it to hexagonal close packing (HCP) but the second article tends to be a bit more mathematical.

I have been investigating the use of these in RPG mapping, but although there is an appealing 'correctness' about them (the mathematical basis, the ability to pack space without gaps, the symmetry when slices are taken through the lattice etc), the real issues for gaming purposes seem to be the difficulty that players/GMs would face in visualising them, and the lack of an obvious coordinate system for referencing them.

Although it pains me, simple cubes with {x,y,z} coordinates look like a much simpler solution, allowing everyone to focus on the gameplay rather than being constantly baffled by the non-trivial choice of mapping standard.

Just my 2 cents, albeit a very late addition to this thread.

*Oh, as an aside for space-themed settings, each cell has twelve adjacent cells (three above, three below, and six around the plane) and this allows a neat constellation/astrology link. Imagine a home sector in the starting cell, and then name each adjacent sector after one of the astrological constellations. Just as hex maps can be decomposed into smaller hexes, FCC cells could be decomposed into smaller cells, allowing each sector named after a constellation to be decomposed into sub-sectors. "Let's set a course for subsector 031 of the Gemini Sector"...*

Stuart
> 13 votes

# Answer
There are two simple 3D analogues of the hexagonal lattice: Hexagonal Close Packing (HCP) and Cubic Close Packing, a.k.a. the Face-Centered Cubic (CCP / FCC) lattice.

Both of these lattices are quite similar: they have the same number of nearest neighbors per site (12) and the same sphere packing density (~74%), and they can both be decomposed into stacked 2D hex lattices.

Of the two, I would consider the CCP lattice somewhat "nicer": it's more symmetrical, having no preferred axis like the HCP lattice. In particular, if you were to sit inside one of the cells of the CCP lattice and looking at one of the nearest neighbor cells, the lattice would look the same regardless of which of the neighbor cells you were looking at. This does not hold true for the HCP lattice.

The cells of the CCP tiling are nice and symmetric rhombic dodecahedra, while those of the HPC are twisted into trapezo-rhombic dodecahedra. Here's a picture of some rhombic dodecahedra tiled to form a CCP lattice from Wikipedia:

(Picture by Wikipedia user AndrewKepert, licensed under GFDL 1.2+ / CC-By-SA 3.0.)

Also note that, as the alternative name "face-centered cubic lattice" suggests, there's a very simple formula for finding the centers of the cells in a CCP lattice: start with a simple cubic lattice, with points at the corners of the cubes, and add new points at the centers of the faces of the cubes. The nearest neighbors of the points at the corners are those on the 12 adjacent faces, while the nearest neighbors of the points on the faces are the 4 on the adjacent corners plus the 8 on the adjacent faces of the two cubes sharing the face on which the center point lies. (With some geometry, you can show that the neighborhoods of all points in fact look the same, even though this construction makes it seem as if the "face points" were different from the "corner points".)

*(Note: The MathWorld page I linked to above seems to contain a mistake, giving the density of the related, non-close-packed "Body-Centered Cubic" lattice also as 74% — it's actually about 68%.)*
> 7 votes

# Answer
I agree with @Cyclops that this is probably better asked on the math stack exchange, but in the mean time you may want to look into the Hexagonal Close Packing structure. It is the densest possible arrangement of spheres in 3D, and while the distance to all neighbours isn't uniform it may be the best you're going to get. The Diamond Cubic lattice has an equal distance to direct neighbours, but it's quite loosely packed, and each point only has four adjacent points.
> 5 votes

---
Tags: geometry, data-structure
---


title: libgdx - handling battery warning

text:
# Question
Title: libgdx - handling battery warning
I want to pause my game when the battery warning on Android pops up. How do I do this? I have a method that pauses the game but how do I call it when the battery warning pops up?

# Answer
> 1 votes
Android does not give you that information if you are not looking for it as far as I know. `onPause` is called due to the fact that you get a pop-up on the screen, which means you are not currently running the GameActivity. You could stop there and design your game in a manner that when an external factor interrupts your activity you should pause the game when `onResume` is being called.

Also to answer the "How Can I monitor battery life", you should follow this tutorial:

http://developer.android.com/training/monitoring-device-state/battery-monitoring.html

However pay attention to the bottom line since polling the battery life consumes mores battery than the actual usefulness of the information it gives you.

# Answer
> 0 votes
Look at this link: https://stackoverflow.com/a/21576506/1892346 . From what I know (I may be wrong) Android will handle pausing itself, the only job that you have to do is to handle Android callbacks (pause and resume methods).

---
Tags: android, libgdx
---


# Question
Title: what's wrong with my lookAt and move forward code?
so am still in the process of getting familiar with libGdx and one of the fun things i love to do is to make basics method for reusability on future projects, and for now am stacked on getting a Sprite rotate toward target (vector2) and then move forward based on that rotation the code am using is this :

```
    // set angle
   public void lookAt(Vector2 target) {

      float angle = (float) Math.atan2(target.y - this.position.y, target.x
            - this.position.x);
      angle = (float) (angle * (180 / Math.PI));

      setAngle(angle);

   }

   // move forward
   public void moveForward() {
      this.position.x += Math.cos(getAngle())*this.speed;
      this.position.y += Math.sin(getAngle())*this.speed;
   }

```

and this is my render method :

```
    @Override
   public void render(float delta) {
      // TODO Auto-generated method stub
      Gdx.gl.glClearColor(0, 0, 0.0f, 1);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

      // groupUpdate();

      Vector3 mousePos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
      camera.unproject(mousePos);
      ball.lookAt(new Vector2(mousePos.x, mousePos.y));
      //

      if (Gdx.input.isTouched()) {
         ball.moveForward();
      }

      batch.begin();
      batch.draw(ball.getSprite(), ball.getPos().x, ball.getPos().y, ball
            .getSprite().getOriginX(), ball.getSprite().getOriginY(), ball
            .getSprite().getWidth(), ball.getSprite().getHeight(), .5f,
            .5f, ball.getAngle());
      batch.end();
   }

```

the goal is to make the ball always look at the mouse cursor, and then move forward when i click, am also using this camera :

```
// create the camera and the SpriteBatch
  camera = new OrthographicCamera();
  camera.setToOrtho(false, 800, 480);

```

aaaand the result was so creepy lol

Thank you

# Answer
> 1 votes
i am really impressed by the build-in method of libGdx, this is what am looking for :

```
// set angle
public void lookAt(Vector2 target) {

    setAngle(target.sub(position).angle());

}

// move forward
public void moveForward() {

    position.add(new Vector2(speed, 0).rotate(getAngle()));
}

```

# Answer
> 1 votes
This part looks suspect to me:

```
  public void moveForward() {
      this.position.x += Math.cos(getAngle())*this.speed;
      this.position.y += Math.sin(getAngle())*this.speed;
   }

```

I'd do that sort of thing using vector maths which is usually faster, something like this (pseudocode):

```
  public void moveForward() {
     Vector2 directionToMouse = mousePosition - this.position;
     directionToMouse.Normalize();
     this.position += directionToMouse * speed;
   }

```

---
Tags: libgdx, rotation, movement
---


title: How to translate along Z axis in OpenTK

text:
# Question
Title: How to translate along Z axis in OpenTK
I am playing around with an OpenGL sample application I downloaded for Xamarin-Android. The sample application produces a rotating colored cube I would simply like to edit it so that the rotating cube is translated along the Z axis and disappears into the distance.

I modified the code by:

* adding an cumulative variable to store my Z distance,
* adding GL.Enable(All.DepthBufferBit) - unsure if I put it in the right place,
* adding GL.Translate(0.0f, 0.0f, Depth) - before the rotate functions,

Result: cube rotates a couple of times then disappears, it seems to be getting clipped out of the frustum.

So my question is what is the correct way to use and initialize the Z buffer and get the cube to travel along the Z axis? I am sure I am missing some function calls but am unsure of what they are and where to put them.

I apologise in advance as this is very basic stuff but am still learning :P, I would appreciate it if anyone could show me the best way to get the cube to still rotate but to also move along the Z axis. I have commented all my modifications in the code:

```
    // This gets called when the drawing surface is ready
    protected override void OnLoad (EventArgs e)
    {
        // this call is optional, and meant to raise delegates
        // in case any are registered
        base.OnLoad (e);

        // UpdateFrame and RenderFrame are called
        // by the render loop. This is takes effect
        // when we use 'Run ()', like below
        UpdateFrame += delegate (object sender, FrameEventArgs args) {
            // Rotate at a constant speed
            for (int i = 0; i < 3; i ++)
                rot [i] += (float) (rateOfRotationPS [i] * args.Time);
        };

        RenderFrame += delegate {
            RenderCube ();
        };

        GL.Enable(All.DepthBufferBit);          //Added by Noob
        GL.Enable(All.CullFace);
        GL.ShadeModel(All.Smooth);

        GL.Hint(All.PerspectiveCorrectionHint, All.Nicest);

        // Run the render loop
        Run (30);
    }

    void RenderCube ()
    {
        GL.Viewport(0, 0, viewportWidth, viewportHeight);

        GL.MatrixMode (All.Projection);
        GL.LoadIdentity ();

        if ( viewportWidth > viewportHeight )
        {
            GL.Ortho(-1.5f, 1.5f, 1.0f, -1.0f, -1.0f, 1.0f);
        }
        else
        {
            GL.Ortho(-1.0f, 1.0f, -1.5f, 1.5f, -1.0f, 1.0f);
        }

        GL.MatrixMode (All.Modelview);
        GL.LoadIdentity ();
        Depth -= 0.02f;                          //Added by Noob
        GL.Translate(0.0f,0.0f,Depth);           //Added by Noob
        GL.Rotate (rot[0], 1.0f, 0.0f, 0.0f);
        GL.Rotate (rot[1], 0.0f, 1.0f, 0.0f);
        GL.Rotate (rot[2], 0.0f, 1.0f, 0.0f);

        GL.ClearColor (0, 0, 0, 1.0f);
        GL.Clear (ClearBufferMask.ColorBufferBit);

        GL.VertexPointer(3, All.Float, 0, cube);
        GL.EnableClientState (All.VertexArray);
        GL.ColorPointer (4, All.Float, 0, cubeColors);
        GL.EnableClientState (All.ColorArray);
        GL.DrawElements(All.Triangles, 36, All.UnsignedByte, triangles);

        SwapBuffers ();
    }

```

# Answer
> 0 votes
You need to translate the cube AFTER you rotate it. The depth buffer has nothing to do with this.

If you first translate it, the vertices will be further away from origin, and then the rotation rotates them in relation to the origin, which results in a disappeared (out of view frustum) cube.

Also, while GL.Rotate and GL.Translate calls are supported, they are long deprecated feature. You should learn about using your own matrices with OpenTK's Matrix4 data structure. You can find great matrix tutorial from here. This probably will save you for some confusion about in which order the rotations and translations should be done.

# Answer
> 0 votes
In order to get correct rotations, you need to translate your cube to the origin, rotate, then translate back to original location. That way, you get a rotation that happens "in place" and not relative to some other location.....

---
Tags: opengl, c#, android, opentk
---


# Question
Title: How can I efficiently update only the entities that matter in a given frame?
I'm making a RTS, which can potentially have lots of units in one map (think *Age of Empires*).

I'm looking for a way to update my units. I want to avoid calling a virtual `Update()` method *every* frame on *every* entity. On the other hand, units that are not in view should still be updated and behave "normally."

I'm assuming this is a fairly standard question; what would be a way to handle this situation?

# Answer
> 2 votes
First, consider a design that avoids the need for a virtual update entirely. The overhead of dynamic dispatch is trivial, but non-zero. More importantly, however, the fact that one is necessary generally suggests that you may have poor *cache coherency* in the storage of your units. That is, you may have something like a `vector<Unit *>` which contains units of various concrete subtypes in effectively random order.

An approach where you store lists of concrete unit types and update each unit type in large blocks has better coherency, and avoids both the indirection needed for the dispatch and the dispatch itself. The outboard component entity architecture is particularly amenable to this.

Related, consider whether the type hierarchy for units makes sense: do you really need inheritance here, or can you instead *compose* the differences between units as data?

Second, use an appropriate spatial partitioning technique to determine which units are more important (for example, visible units are probably very important) and must have constant, immediate updates versus which units are far away and don't need as frequent updates.

Units with less priority can be updated less frequently, such as by subdividing them into N groups which are updated every N frames, effectively amortizing the cost of their update over multiple frames of update time.

There's no magic bullet: you basically need to make sure your updates are cheap (make sure you profile, so you know the updates are actually expensive, where they are expensive, and how to cheapen them) and that you do fewer of them (prioritizing the units that matter over ones that are less important).

# Answer
> 0 votes
You can amortize some things over multiple frames. I am sure `Update (...)` consists of multiple potentially independent tasks, that you could easily queue up.

Rather than completely deferring distant/unimportant unit processing and then having the unpleasant requirement of completing the entire update in the span of a single *future* frame, you could simply do half of their processing on one frame and the other half the next and only commit the end result when all sub-tasks are done. The net result is the same as if you only updated them once every other frame, but you will have less trouble meeting deadlines in some cases if you split the work that way.

I realize that in this question is not so much about real-time computing :P But the whole thought process behind meeting deadlines is still useful... you can prioritize certain tasks such as position update so that they *appear* more responsive to the player. Even if a unit is not completely finished thinking, if it knows where it should be spatially before the next frame is drawn, go ahead and put the unit there.

You can vary the priority of each sub-task inside of your `Update (...)` according to distance, age, rank, or any number of different metrics. In fact, rather than calling an `Update (...)` function at all per-entity, you might consider a (priority) queue of tasks that need to be done. Your entities can add their tasks to this queue every time they need to think, and doing it this way makes distributing the workload across threads a lot easier.

The bottom line is that generally not everything needs to be finished every frame. If your requirement is that a unit has to completely update itself (complete every one of its update tasks) in the period of one frame, then that can create some awkward situations where framerates start to vary wildly even if you do only process 1/N-many units per-frame. If, instead, you prioritize certain aspects of unit updates you can do the important things more frequently and even tolerate situations where some update tasks take an unpredictable amount of time to complete.

---
Tags: ai, entity-system, game-loop, events, realtime
---


# Question
Title: libgdx rotation (animation, arrays) issues and help needed
well i am a noob at java and libgdx. i got the homing bullet working with the help of someone. now i am smashing my head as to how i can make it rotate so it faces the ball (which is the main character) when it goes around it or when it is coming towards it. the bullet is facing \<--- and the code below is what i have done so far. also i used sprites for the bullet and also animation method.

Also how do i make it an array/arraylist which is best so i can have multiple bullets at random or placed places. i tried many things nothing workd :(

thank you for the help.

// below is the bullet or enemy if you want to call it.

```
public class Bullet extends Sprite {

  public static final float BULLET_HOMING = 6000;
  public static final float BULLET_SPEED = 300;
  private Vector2 velocity;
  private float lifetime;

  public Bullet(float x, float y) {
     velocity = new Vector2(0, 0);
     setPosition(x, y);
  }

  public void update(float delta) {
     float targetX = GameWorld.getBall().getX();
     float targetY = GameWorld.getBall().getY();
     float dx = targetX - getX();
     float dy = targetY - getY();

     float distToTarget = (float) Math.sqrt(dx * dx + dy * dy);
     dx /= distToTarget;
     dy /= distToTarget;
     dx *= BULLET_HOMING;
     dy *= BULLET_HOMING;
     velocity.x += dx * delta;
     velocity.y += dy * delta;

     float vMag = (float) Math.sqrt(velocity.x * velocity.x + velocity.y * velocity.y);
     velocity.x /= vMag;
     velocity.y /= vMag;
     velocity.x *= BULLET_SPEED;
     velocity.y *= BULLET_SPEED;

     Vector2 v = velocity.cpy().scl(delta);
     setPosition(getX() + v.x, getY() + v.y);
     setOriginCenter();
     setRotation(velocity.angle());
     lifetime += delta;
     setRegion(AssetLoader.bulletAnimation.getKeyFrame(lifetime));
  }
}

```

// this is where i load the images.

```
public class AssetLoader {
public static Animation bulletAnimation;
public static Sprite bullet1, bullet2;

public static void load() {

    texture = new Texture(Gdx.files.internal("SpriteN1.png"));
    texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);

    bullet1 = new Sprite(texture, 380, 350, 45, 20);
    bullet1.flip(false, true);

    bullet2 = new Sprite(texture, 425, 350, 45, 20);
    bullet2.flip(false, true);

    Sprite[] bullets = { bullet1, bullet2 };
    bulletAnimation = new Animation(0.06f, aims);
    bulletAnimation.setPlayMode(Animation.PlayMode.LOOP);
}

public static void dispose() {
    // We must dispose of the texture when we are finished.
    texture.dispose();
}

```

// this is for the rendering of the images etc

```
public class GameRenderer {
private Bullet bullet;
private Ball ball;

public GameRenderer(GameWorld world) {
    myWorld = world;
    cam = new OrthographicCamera();
    cam.setToOrtho(true, 480, 320);

    batcher = new SpriteBatch();
    // Attach batcher to camera
    batcher.setProjectionMatrix(cam.combined);

    shapeRenderer = new ShapeRenderer();
    shapeRenderer.setProjectionMatrix(cam.combined);

    // Call helper methods to initialize instance variables
    initGameObjects();
    initAssets();
}

private void initGameObjects() {
   ball = GameWorld.getBall();
   bullet = myWorld.getBullet();
    scroller = myWorld.getScroller();
}

private void initAssets() {
    ballAnimation = AssetLoader.ballAnimation;
    bulletAnimation = AssetLoader.bulletAnimation;
}

public void render(float runTime) {

   Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);

    batcher.begin();
    // Disable transparency
    // This is good for performance when drawing images that do not require
    // transparency.
    batcher.disableBlending();

    // The ball needs transparency, so we enable that again.
    batcher.enableBlending();

    batcher.draw(AssetLoader.ballAnimation.getKeyFrame(runTime), ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight());

    batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(), bullet.getY());

    // End SpriteBatch
    batcher.end();
    }
}

```

// this is to load the image etc on the screen i guess

```
public class GameWorld {

public static Ball ball;
private Bullet bullet;
private ScrollHandler scroller;

public GameWorld() {
   ball = new Ball(480, 273, 32, 32);
   bullet = new Bullet(10, 10);
    scroller = new ScrollHandler(0);
}

public void update(float delta) {
    ball.update(delta);
    bullet.update(delta);
    scroller.update(delta);
}

public static Ball getBall() {
    return ball;
}

public ScrollHandler getScroller() {
    return scroller;
}

public Bullet getBullet() {
   return bullet;
 }
}

```

so there is the whole thing. the images are loaded via the AssetLoader then to the GameRenderer and GameWorld via the Bullet class. i am guessing that is how it is. sorry newbie so still learning.

thank you in advace for the help or any advice.

# Answer
> 1 votes
For your **first question**, what you'd need to do is to use a SpriteBatch `draw()` method that includes setting a rotation. You can use this draw method that takes in a rotation argument. Now, the question is how to calculate the rotation that is required. This requires a little bit of trigonometry, and also depends on how your bullet image looks like. Refer to the figure below.

Assuming that you bullet image is like that shown above, where it is pointing up. Then, you can calculate the angle using the `atan2` function. The parameters being passed in would just be `deltaY` and `deltaX`, which is the distance between your bullet and your target for both the y-axis and x-axis respectively.

For your **second question**, instead of having a single `private Bullet bullet` in your GameWorld, you would want to have an Array of bullets. You can declare 10 bullets with random positions between \[-10,10\] for both their x-position and y-position like this.

```
   private Array<Bullet> bullets;

   public GameWorld() {

      bullets = new Array<Bullet>();

      Bullet bullet = null;
      float bulletX = 0.0f;
      float bulletY = 0.0f;
      for (int i=0; i < 10; i++) {
         bulletX = MathUtils.random(-10, 10);
         bulletY = MathUtils.random(-10, 10);
         bullet = new Bullet(bulletX, bulletY);

         // add the bullet to your array so you can reference them later
         bullets.add(bullet)
      }

      ...
   }

```

---
Tags: libgdx, rotation
---


# Question
Title: 2D metaball liquid effect - how to feed output of one rendering pass as input to another shader
I'm attempting to make a shader for unity3d web project. I want to implement something like in the great answer by DMGregory in this question. in order to achieve a final look something like this..

Its metaballs with specular and shading.
The steps to make this shader are.
1. Convert the feathered blobs into a heightmap.
2. Generate a normalmap from the heightmap
3. Feed the normal map and height map into a standard unity shader, for instance transparent parallax specular.

I pretty much have all the pieces I need assembled but I am new to shaders and need help putting them together

I can generate a heightmap from the blobs using some fragment shader code I wrote (I'm just using the red channel here cus i dont know if you can access the brightness)

```
    half4 frag (v2f i) : COLOR{
        half4 texcol,finalColor;
        texcol = tex2D (_MainTex, i.uv);
        finalColor=_MyColor;
        if(texcol.r<_botmcut)
        {
            finalColor.r= 0;
        }
        else if((texcol.r>_topcut))
        {
            finalColor.r= 0;
        }
        else
        {
            float r = _topcut-_botmcut;
            float xpos = _topcut - texcol.r;

            finalColor.r= (_botmcut + sqrt((xpos*xpos)-(r*r)))/_constant;
        }
        return finalColor;
    }

```

turns these blobs..

into this heightmap

Also I've found some CG code that generates a normal map from a height map. The bit of code that makes the normal map from finite differences is here

```
    void surf (Input IN, inout SurfaceOutput o)
                {
                    o.Albedo = fixed3(0.5);

                    float3 normal = UnpackNormal(tex2D(_BumpMap, IN.uv_MainTex));

                    float me = tex2D(_HeightMap,IN.uv_MainTex).x;
                    float n = tex2D(_HeightMap,float2(IN.uv_MainTex.x,IN.uv_MainTex.y+1.0/_HeightmapDimY)).x;
                    float s = tex2D(_HeightMap,float2(IN.uv_MainTex.x,IN.uv_MainTex.y-1.0/_HeightmapDimY)).x;
                    float e = tex2D(_HeightMap,float2(IN.uv_MainTex.x-1.0/_HeightmapDimX,IN.uv_MainTex.y)).x;
                    float w = tex2D(_HeightMap,float2(IN.uv_MainTex.x+1.0/_HeightmapDimX,IN.uv_MainTex.y)).x;

                    float3 norm = normal;
                    float3 temp = norm; //a temporary vector that is not parallel to norm
                    if(norm.x==1)
                        temp.y+=0.5;
                    else
                        temp.x+=0.5;

                    //form a basis with norm being one of the axes:
                    float3 perp1 = normalize(cross(norm,temp));
                    float3 perp2 = normalize(cross(norm,perp1));

                    //use the basis to move the normal in its own space by the offset
                    float3 normalOffset = -_HeightmapStrength * ( ( (n-me) - (s-me) ) * perp1 + ( ( e - me ) - ( w - me ) ) * perp2 );
                    norm += normalOffset;
                    norm = normalize(norm);

                    o.Normal = norm;
                }

```

Also here is the built-in transparent parallax specular shader for unity.

```
    Shader "Transparent/Parallax Specular" {
    Properties {
        _Color ("Main Color", Color) = (1,1,1,1)
        _SpecColor ("Specular Color", Color) = (0.5, 0.5, 0.5, 0)
        _Shininess ("Shininess", Range (0.01, 1)) = 0.078125
        _Parallax ("Height", Range (0.005, 0.08)) = 0.02
        _MainTex ("Base (RGB) TransGloss (A)", 2D) = "white" {}
        _BumpMap ("Normalmap", 2D) = "bump" {}
        _ParallaxMap ("Heightmap (A)", 2D) = "black" {}
    }

    SubShader {
        Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
        LOD 600

    CGPROGRAM
    #pragma surface surf BlinnPhong alpha
    #pragma exclude_renderers flash

    sampler2D _MainTex;
    sampler2D _BumpMap;
    sampler2D _ParallaxMap;
    fixed4 _Color;
    half _Shininess;
    float _Parallax;

    struct Input {
        float2 uv_MainTex;
        float2 uv_BumpMap;
        float3 viewDir;
    };

    void surf (Input IN, inout SurfaceOutput o) {
        half h = tex2D (_ParallaxMap, IN.uv_BumpMap).w;
        float2 offset = ParallaxOffset (h, _Parallax, IN.viewDir);
        IN.uv_MainTex += offset;
        IN.uv_BumpMap += offset;

        fixed4 tex = tex2D(_MainTex, IN.uv_MainTex);
        o.Albedo = tex.rgb * _Color.rgb;
        o.Gloss = tex.a;
        o.Alpha = tex.a * _Color.a;
        o.Specular = _Shininess;
        o.Normal = UnpackNormal(tex2D(_BumpMap, IN.uv_BumpMap));
    }
    ENDCG
    }

    FallBack "Transparent/Bumped Specular"
    }

```

# Answer
> 1 votes
One way to do this is with OnPostRender and Graphics.Blit.

First, create a camera that views the input blobs, set its depth so it renders before your other cameras, and attach to it a script something like this one:

```
public class TextureExtractor : MonoBehaviour
{
  public RenderTexture normalMap;
  public RenderTexture diffuseMap;

  public Material normalExtractionMaterial;
  public Material diffuseExtractionMaterial;

  private RenderTexture _heightfield;

  void Start()
  {
     // Here I assume your blobs have only one channel of information, and that you want high precision/range (floating point format)
     _heightfield = new RenderTexture(normalMap.width, normalMap.height, 0, RenderTextureFormat.RFloat);

     camera.targetTexture = _heightfield;
     camera.aspect = _heightfield.width/(float)_heightfield.height;

     // This allows floating point rendering outside the 0-1 range, reducing banding and plateaus in the heightmap.
     camera.hdr = true;
  }

  // This gets called each time the camera to which the script is attached finishes rendering its view.
  void OnPostRender()
  {
     // Uses the normalExtractionMaterial's shader to populate normalMap from _heightfield.
     Graphics.Blit(_heightfield, normalMap, normalExtractionMaterial);

     // Uses the diffuseExtractionMaterial's shader to populate diffuseMap from _heightfield.
     Graphics.Blit(_heightfield, diffuseMap, diffuseExtractionMaterial);
  }
}

```

Create two new RenderTextures in your Assets folder for the normal and diffuse. Then create materials with the shaders you want to use to generate the normals & diffuse out of the heightmap. Assign all of these assets to the TextureExtractor instance on your blob-viewing camera.

You can then re-use the normal & diffuse RenderTextures as texture inputs on other materials elsewhere in your scene.

What's happening under the hood is that Graphics.Blit sets the input texture (here, \_heightfield) as the shader's \_MainTex, and then renders a full-screen quad into the destination texture using this shader. (For example, if the shader is UnlitTexture, this has the effect of copying one texture's contents into the other, up/down-sampling as needed). The destination texture's contents are now updated for any other materials that are referencing it.

You can chain these blits as deep as you need, if you want to process the blobs into an intermediate texture (say, a blurred version to smooth it out), then transform that into a different intermediate (say, a scaled/thresholded version to get the contours you want), and then finally build your output textures out of the end of that chain.

For intermediate processes where the texture format & resolution doesn't change, OnRenderImage(src, dest) may also be useful - it's designed for doing one blit per call, sequentially, using the previous output as the next input. It gets called after rendering the scene is complete, but before OnPostRender, so it's the typical home for postprocess image effects.

---
Tags: unity, shaders, water
---


# Question
Title: Wall jumping collision detection anomaly
I'm creating a game where the player ascends a tower by wall jumping his way to the top. When the player has collided with the right wall they can only jump left and vice versa. Here is my current implementation:

```
    if(wallCollision() == "left"){
        player.setPosX(0);
        player.setVelX(0);
        ignoreCollisions = true;
        player.setCanJump(true);
        player.setFacingLeft(false);
    } else if (wallCollision() == "right"){
        player.setPosX(screenWidth-playerWidth*2);
        player.setVelX(0);
        ignoreCollisions = true;
        player.setCanJump(true);
        player.setFacingLeft(true);
    } else{
        player.setVelY(player.getVelY() + gravity);
    }

```

and

```
private String wallCollision(){
    if(player.getPosX() < playerWidth && !ignoreCollisions)
        return "left";
    else if(player.getPosX() > screenWidth - playerWidth*2 && !ignoreCollisions)
        return "right";
    else{
        timeToJump += Gdx.graphics.getDeltaTime();
        if(timeToJump > 0.50f){
            timeToJump = 0;
            ignoreCollisions = false;
        }
        return "jumping";
    }
}

```

If the player is colliding with the left wall it will switch between the states `left` and `jumping` repeatedly due to the varible `ignoreCollisions` being switched repeatedly in collision checks. This will give a chance to either jump as intended or simply ascend vertically instead of diagonally.

I can't figure out an implementation that will reliably make sure the player jumps as intended. Does anyone have any pointers?

# Answer
> 1 votes
It seems your left limit for detecting collision is playerWidth, but when you detect a collision on the left, you reset the x coordinate to 0.

```
if(wallCollision() == "left"){
    player.setPosX(0); //Should be player.setPosX(playerWidth);

```

**\[EDIT\]**

After seen your images I notice `playerWidth actually` represents half the player width, and your character X coordinate is that of it's left side. In that case, try this, detect left collision when `player.getPosX() < 0`, and reset the pos to 0 as you're doing now:

```
if(wallCollision() == "left"){
    player.setPosX(0);
    player.setVelX(0);
    ignoreCollisions = true;
    player.setCanJump(true);
    player.setFacingLeft(false);
} else if (wallCollision() == "right"){
    player.setPosX(screenWidth-playerWidth*2);
    player.setVelX(0);
    ignoreCollisions = true;
    player.setCanJump(true);
    player.setFacingLeft(true);
} else{
    player.setVelY(player.getVelY() + gravity);
}

```

and:

```
private String wallCollision(){
    if(player.getPosX() < 0 && !ignoreCollisions)
        return "left";
    else if(player.getPosX() > screenWidth - playerWidth*2 && !ignoreCollisions)
        return "right";
    else{
        timeToJump += Gdx.graphics.getDeltaTime();
        if(timeToJump > 0.50f){
            timeToJump = 0;
            ignoreCollisions = false;
        }
        return "jumping";
    }
}

```

# Answer
> 1 votes
I agree with @jspurim that your collision bounds checking, but that is another matter. You are asking about inconsistent jumping off of walls due to the `ignoreCollision` flag flip-flopping, right?

From what I gather reading the code you have posted, when the player jumps and collides with a wall, they stick to that wall and begin to climb vertically. After a brief moment the player can then jump off the wall, or continue climbing the wall they are currently stuck to. The flip-flopping is happening because after the short pause you say it is ok to stop ingnoring collision, when in fact the player is still running up the wall and there is no need to check for wall collisions yet.

Try moving `ignoreCollisions = false;` out of `wallCollision()` and put it in the code where the player actually jumps off of the wall.

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


# Question
Title: Are there any reasons to use Legacy (2.X) OpenGL?
The benefits are well documented of the Modern OpenGL 3.X & 4.X API's, but I'm wondering if there are ANY benefits to keeping with the old OpenGL, Or if learning OpenGL 2.X is a complete waste of time now no matter what?

Particularly I've wondered if using the OpenGL 2.X API is appropriate if the target platform had graphics hardware capable of only up to OpenGL 2.X. Would a driver update on said target platform allow programs compiled using the Modern OpenGL API's to be released on this old platform? If they both work, which would be faster?

Thanks

# Answer
> 4 votes
The legacy OpenGL API does have a purpose; it keeps support for the older systems which couldn't support programmable shaders and the other virtues of modern OpenGL.

It's also useful for writing quick applications which don't really need the performance advantages of shaders and vertex buffers.

Answer to your second question : Modern OpenGL features can only occasionally work on legacy cards. Newer graphics cards provide hardware-level systems for utilizing these newer features, which gives them such a large boost. Some OpenGL features can be used on older cards through software extensions. The performance of these extensions is usually far less than that on a modern card, but it does work.

---
Tags: opengl, graphics
---


title: How do you author HDR content?

text:
# Question
Title: How do you author HDR content?
How do you make it easy for your artists to author content for an HDR renderer? What kinds of tools should you provide, and what workflows need to change, in going from LDR to HDR?

Note that I'm not asking about the technical aspects of implementing an HDR renderer, but about best practices for creating materials and lighting in HDR. I've googled around a bit, but there doesn't seem to be much about this topic on the web. Can anyone point me to some good resources on this, or share their own experiences?

Some specific points:

* Lighting - how can lighting artists pick HDR light colors? Do they have a standard LDR color picker and then a multiplier? Is the multiplier in gamma or linear space? Maybe instead of a multiplier it's a log-luminance? Or a physical brightness level, like the number of lumens? How will they know what multiplier/luminance/brightness is "correct" for a given light?
* Materials - how can texture artists make emissive color maps, such as neon signs, TV screens, skyboxes, etc? Can you paint one as a regular LDR (8-bit-per-channel) image and apply a multiplier (or log-luminance, etc.)? Are there cases where it's necessary to actually paint HDR images? If so, how do you go about this in Photoshop (or other software)?

# Answer
Well, three years later and I've just written a blog post about authoring HDR content, so now I can answer my own question. :)

To summarize,

* A good way to handle the wide range of HDR brightness values is by using a logarithmic scale. Photographers have such a scale that they've been using for decades, called exposure value or EV.
* Using EV in your engine/tools is handy since values measured in real life with a photographer's spot meter can be used as reference data for setting up in-game lighting. Photoshop also uses EV (although it doesn't call it that) in its 32-bit mode.
* Color pickers for light sources, emissive materials and so on can have the usual LDR RGB components combined with an EV component that scales their overall HDR brightness. This is handy to prevent accidentally changing color when you only wanted to change brightness, or vice versa.
* It's not necessary to have HDR textures for the usual diffuse and specular maps, but it *is* useful for emissive textures. BC6 compression is needed here, because BC1 textures show horrible banding and artifacts if they're scaled up to a high brightness (e.g. for neon signs).
* It's usually not necessary to actually paint emissive textures in floating-point. Photoshop 16-bit mode (which is fixed-point) will probably suffice for emissive textures. However, Photoshop 32-bit mode does provide pretty good floating-point image editing support if it's needed.
> 1 votes

# Answer
I think we're still somehow in the "caveman days" Patrick Hugues describes in his comments.

You don't want details about renderer implementations, but let me clarify things a bit anyway: you'll understand why. HDR in game engines is mostly about having "wider" values for the rendering output (the framebuffer). Typically 16 bits floating point that can go above 1.0, instead of 8 bits integers that just give us 256 values in the \[0,1\] range. This output is then converted to LDR using a tone mapper, so the screen can display it. To me, the real "HDR authoring" would be in tweaking this tone mapper, so you'll want to give as much control as you can to your artists on this. There will be some kind of shader involved, so either you've got technical artists that can deal with it, or you hardcode it and expose the most useful parameters.

I'm not sure that you'll necessarily *need* 16 bits lights, except maybe to create lights that emit "whiter than white". But if you want to, in whatever editor you use for your lights, you'll need some kind of color picker or a bunch of sliders that gives you those floating point values. Oh, that's if you want a GUI, you'll probably just start with plain text floating point values in a file.

HDR textures (16 bits per channel) exist but aren't widely used, maybe just because that would take so much more memory than regular LDR textures (8 bits per channel). I also suspect more hardware limitations on current-gen consoles, so most of the big game engines around don't push this too much. For instancce, it seems that it's a bit tricky to import a HDR texture for use with the UDK. Nevertheless, to author 16 bits textures you'll need software that supports it, such as Photoshop. There are probably others, but it doesn't seem that frequent, e.g. ~~it's~~ it was a long-standing request for GIMP ~~that's still pending~~. You'll also have to use a 16 bits aware image format, such as PNG.
> 5 votes

# Answer
like lorancou said, you dont really author hdr content since it generally dynamic to the amount of light. But, you could probably mimic it in a lightmap which would just involve modifying any precalculation shaders to take that into account.
> 1 votes

---
Tags: graphics, art, hdr
---


# Question
Title: What software can I use to animate my character in Unity3D?
I am new in game development and I want to know what software can help me to create good animations for my 3rd person character.

# Answer
Most Many 3D modeling tools have animation capabilities. If you already have a model, find a tool such as Blender, 3D Max, Maya, etc. (the list goes on and on) that can open the respective format and you are ready to go. There are literally thousands of tutorials flying around that should teach you everything to get started in the respective program.

Regarding *good* animations: It highly depends and your capabilities and experience. With any of the commonly used tools great results can be achieved.

PS: Since you are just getting started, Blender is probably your best bet, given that is does not cost any license fees. A good starting point would then be this tutorial page. Additional Blender support can be found here.
> 1 votes

---
Tags: animation
---


# Question
Title: Textures selectively not applying in Unity
On certain imported objects (fbx) in Unity, upon applying a material, only the base colour of the material is applied, with none of the tiled texture showing. This isn't universal; on a test model only some submeshes didn't show the texture, while some did. I have tried every combination of import/calculate normals/tangents to no avail.

FYI I'm not exactly experienced with the software or gamedev in general; this is to make a small static scene with 3-4 objects max. One model tested was created in 3DSMax, the other in Blender. I've had this happen on every export from Blender, but only some submeshes from the 3DSMax model (internet sourced to test the problem)

# Answer
I'm not sure it's your exact problem but I had similar issues.

It looks like Blender doesn't generate `UV` coords by default. Even if you can render your object with texture in Blender - it doesn't mean you'll have `UVs` in the exported mesh. You need to explicitly add some UV channel - I don't know Blender very well so you need to look for some tutorials for this (But it's very simple, if you know where to click).

In 3D MAX, when you create a basic object and select `Generate mapping coords` you'll get the `UVs` out of the box.

There's also a simple way to verify if that's the case. When your mesh doesn't have an `UV` channel but it's used in the rendering, then your `UV` values will be set up to defaults `(0,0)` \- which means that some corner texel will be used as a texture for entire object. Now, if you move or change your texture, so texels on the corners will have different color - your mesh should also change the color during rendering.
> 1 votes

---
Tags: unity, textures, blender, fbx
---


# Question
Title: How do I measure the bounds of a string in PyGame?
I am trying to position some text on my screen using pygame, and knowing the size of the string would help.

When using C# and XNA I could use `SpriteFont.MeasureString("Hello World")` to get the size of the rendered string.

Is there any way to do something similar in pygame?

# Answer
You can use the size method

> **size()**
> size(text) -\> (width, height)
>
> Returns the dimensions needed to render the text. This can be used to help determine the positioning needed for text before it isrendered. It can also be used for wordwrapping and other layout effects.

Here is an example

```
myFont = pygame.font.Font(None, fontSize)

width  = myFont.size("Hello World")[0]
heigth = myFont.size("Hello World")[1]

```
> 6 votes

---
Tags: python, pygame
---


# Question
Title: projection / view matrix: the object is bigger than it should and depth does not affect vertices
I'm currently trying to write a C 3D software rendering engine from scratch just for fun and to have an insight on what OpenGL does behind the scene and what 90's programmers had to do on DOS.

I have written my own matrix library and tested it without noticing any issues, but when I tried projecting the vertices of a simple 2x2 cube at 0,0 as seen by a basic camera at 0,0,10, the cube seems to appear way bigger than the application's window. If I scale the vertices' coordinates down by 8 times I can see a proper cube centered on the screen. This cube doesn't seem to be in perspective: wheen seen from the front, the back vertices pe rfectly overlap with the front ones, so I'm quite sure it's not correct.

this is how I create the view and projection matrices (vec4\_initd initializes the vectors with w=0, vec4\_initw initializes the vectors with w=1):

```
void mat4_lookatlh(mat4 *m, const vec4 *pos, const vec4 *target, const vec4 *updirection) {
    vec4 fwd, right, up;

    // fwd = norm(pos - target)
    fwd = *target;
    vec4_sub(&fwd, pos);
    vec4_norm(&fwd);

    // right = norm(cross(updirection, fwd))
    vec4_cross(updirection, &fwd, &right);
    vec4_norm(&right);

    // up = cross(right, forward)
    vec4_cross(&fwd, &right, &up);

    // orientation and translation matrices combined
    vec4_initd(&m->a, right.x, up.x, fwd.x);
    vec4_initd(&m->b, right.y, up.y, fwd.y);
    vec4_initd(&m->c, right.z, up.z, fwd.z);
    vec4_initw(&m->d, -vec4_dot(&right, pos), -vec4_dot(&up, pos), -vec4_dot(&fwd, pos));
}

void mat4_perspectivefovrh(mat4 *m, float fovdegrees, float aspectratio, float near, float far) {
    float h = 1.f / tanf(ftoradians(fovdegrees / 2.f));
    float w = h / aspectratio;

    vec4_initd(&m->a, w, 0.f, 0.f);
    vec4_initd(&m->b, 0.f, h, 0.f);
    vec4_initw(&m->c, 0.f, 0.f, -far / (near - far));
    vec4_initd(&m->d, 0.f, 0.f, (near * far) / (near - far));
}

```

this is how I project my vertices:

```
void device_project(device *d, const vec4 *coord, const mat4 *transform, int *projx, int *projy) {
    vec4 result;

    mat4_mul(transform, coord, &result);
    *projx = result.x * d->w + d->w / 2;
    *projy = result.y * d->h + d->h / 2;
}

void device_rendervertices(device *d, const camera *camera, const mesh meshes[], int nmeshes, const rgba *color) {
    int i, j;
    mat4 view, projection, world, transform, projview;
    mat4 translation, rotx, roty, rotz, transrotz, transrotzy;
    int projx, projy;

    // vec4_unity = (0.f, 1.f, 0.f, 0.f)
    mat4_lookatlh(&view, &camera->pos, &camera->target, &vec4_unity);
    mat4_perspectivefovrh(&projection, 45.f, (float)d->w / (float)d->h, 0.1f, 1.f);

    for (i = 0; i < nmeshes; i++) {
        // world matrix = translation * rotz * roty * rotx
        mat4_translatev(&translation, meshes[i].pos);
        mat4_rotatex(&rotx, ftoradians(meshes[i].rotx));
        mat4_rotatey(&roty, ftoradians(meshes[i].roty));
        mat4_rotatez(&rotz, ftoradians(meshes[i].rotz));
        mat4_mulm(&translation, &rotz, &transrotz); // transrotz = translation * rotz
        mat4_mulm(&transrotz, &roty, &transrotzy); // transrotzy = transrotz * roty = translation * rotz * roty
        mat4_mulm(&transrotzy, &rotx, &world); // world = transrotzy * rotx = translation * rotz * roty * rotx

        // transform matrix
        mat4_mulm(&projection, &view, &projview); // projview = projection * view
        mat4_mulm(&projview, &world, &transform); // transform = projview * world = projection * view * world

        for (j = 0; j < meshes[i].nvertices; j++) {
            device_project(d, &meshes[i].vertices[j], &transform, &projx, &projy);
            device_putpixel(d, projx, projy, color);
        }
    }
}

```

this is how the cube and camera are initialized:

```
// test mesh
cube = &meshlist[0];
mesh_init(cube, "Cube", 8);
cube->rotx = 0.f;
cube->roty = 0.f;
cube->rotz = 0.f;
vec4_initw(&cube->pos, 0.f, 0.f, 0.f);
vec4_initw(&cube->vertices[0], -1.f, 1.f, 1.f);
vec4_initw(&cube->vertices[1], 1.f, 1.f, 1.f);
vec4_initw(&cube->vertices[2], -1.f, -1.f, 1.f);
vec4_initw(&cube->vertices[3], -1.f, -1.f, -1.f);
vec4_initw(&cube->vertices[4], -1.f, 1.f, -1.f);
vec4_initw(&cube->vertices[5], 1.f, 1.f, -1.f);
vec4_initw(&cube->vertices[6], 1.f, -1.f, 1.f);
vec4_initw(&cube->vertices[7], 1.f, -1.f, -1.f);

// main camera
vec4_initw(&maincamera.pos, 0.f, 0.f, 10.f);
maincamera.target = vec4_zerow;

```

and, just to be sure, this is how I compute matrix multiplications:

```
void mat4_mul(const mat4 *m, const vec4 *va, vec4 *vb) {
    vb->x = m->a.x * va->x + m->b.x * va->y + m->c.x * va->z + m->d.x * va->w;
    vb->y = m->a.y * va->x + m->b.y * va->y + m->c.y * va->z + m->d.y * va->w;
    vb->z = m->a.z * va->x + m->b.z * va->y + m->c.z * va->z + m->d.z * va->w;
    vb->w = m->a.w * va->x + m->b.w * va->y + m->c.w * va->z + m->d.w * va->w;
}

void mat4_mulm(const mat4 *ma, const mat4 *mb, mat4 *mc) {
     mat4_mul(ma, &mb->a, &mc->a);
     mat4_mul(ma, &mb->b, &mc->b);
     mat4_mul(ma, &mb->c, &mc->c);
     mat4_mul(ma, &mb->d, &mc->d);
}

```

# Answer
> 1 votes
It is not in perspective because `device_project (...)` does not divide by `w`.

Given a typical perspective projection matrix, the `z` component of the last row/column is usually +/- **1.0** and everything else in the row/column is **0.0**.

### OpenGL Perspective Projection Matrix (right-handed eye-space --\> left-handed clip-space):

(source: songho.ca)

This produces `w = +/-z` in the transformed vertex (depending on whether the projection matrix is setup to flip the Z-axis - GL flips the Z-axis, D3D does not). Thus the homogeneous divide will actually scale geometry based on distance down the Z-axis and this is why it is sometimes called the perspective divide.

---
Tags: matrix, projection, view, software-rendering
---