# Question
Title: Multiple collisions within a single frame cycle?
So say you want to simulate several objects in two dimensions, just bouncing around in a finite space. Using AABB and sweep tests, it shouldn't be that complicated to calculate single collisions between objects. But if you want to have an object bounce off another surface in the same frame (one collision), how do you account for any additional collisions after that first one? This might not make much sense, so I put a little graphic together to explain what I mean.

So say all this is happening in one frame cycle. The gray box moves up and bounces off the wall on the top; that's easy enough. That orange box is the problem, though. How do I calculate that collision as well (where the two translucent boxes are)? OR, if the frame rate is high enough, does it even matter? Thanks!

# Answer
> 2 votes
It's quite a special case you are describing :) Most physics engines would probably not handle it *exactly* but would do something that's "good enough". If you really want something like this then you might want to look into *Continous Collision Detection* (CCD). I think Box2D can handle this for some objects by declaring them as "bullet" for example so you could check out the source for that. You might also want to look into *speculative contacts* which I think is described in a good way at Jitter physics.

If your requirements are not extreme or your timestep small then a simpler solution might be acceptable. One way to handle it is by running several iterations of the collision handling and recalculating closing velocities for the involved bodies (collision island) after each handled collision. This would, however, not actually detect new collisions like you describe but I don't think it will be necessary for most cases.

# Answer
> 0 votes
As a potential solution, you could break down your updates and frames so that you update multiple times per render frame. This comes with a change where you have to account for the number of times you are updating because if you simply update 10 times more at the same speed your game just moves 10x faster with 10x less frames.

Once you have that accounted for, you will find that if you are updating 10 times per frame, the first collision will occur perhaps on update 4, handle for it by adjusting your velocity, etc. and then maybe on update 7 the final collision occurs and you can handle it accordingly and use the proper velocity, etc. for the last 3 updates.

Obviously this is going to add some processing time to your game so make sure you are only updating what is necessary for your situation. You can in fact, take this one step further and separate things out even more. You could draw every X updates, handle input every Y updates, update physics every Z udpates, etc. Also, make sure that the number of times you update makes sense for how your game works. If you don't have to update 10 times a frame because not that much happens within a single frame, then lower the number of updates.

---
Tags: collision-detection, physics
---


title: How to make smooth animations

text:
# Question
Title: How to make smooth animations
Say I want to write a card game. I have a hand of cards and I want to be able to draw a smooth animation of a card moving from the hand to the table. I am looking for suggestions on how to elegantly represent the situation in data structures. Of course, I am not solely interested in cards, it seems to be a problem with more complex user interfaces in general.

The obvious representation of the hand is an array/list of cards. Given a rectangle in 2d space this hand is trivial to draw. When playing a card I can remove that card from the array and create a new structure that draws that card moving along any curve I like. The problem is then how the hand is drawn. In trivial implementation the hand in one instant shrinks in width by one card (as the array was replaced). Also, the selected card is now either above or bellow the hand (as it is drawn before or after drawing the hand), while a moment ago it was between the two cards next to it. These problems I'm not sure how to solve. They get even worse if trying to move several cards at once.

It would most likely work to make every card a separate body aware of it's position and movement in the plane (and possibly, the z axis to make overlaps work, as OpenGL allows this). It does seem like poor design to allow a system that almost always stays in a fixed shape too much flexibility. It also looks like a recipe for unexplainable bugs.

I would like to hear from someone who has done this, what is the best approach. To put it briefly, "specific and restrictive representation in data structures" versus "entirely free environment with some external limits".

Thanks a lot

# Answer
> 1 votes
Separate the idea of viewing the cards, and handling the logic for the card game.

The view is 5 cards (say) lying face up (or down) on the table, slightly overlapping. The actual hand is, as you said, an list of card objects. The rules of the game operate on the list, because this is the problem domain for your program, the visuals work with the view.

When you then take a card out and place it on the table, the action is first checked to be legal by the domain code, then it makes the changes to the lists holding the cards, and give a description of what happened to the view. This description is as simple as `"Three of spades" discarded`, in whichever format works best for your language (object/enum/even string).

Now the view simply animates the visual representation of the card being thrown into the discard pile, or placed face up in a specific spot, depending on the cardgame itself. Because it now has a gap where the card used to be, it can now animate the cards sliding together, or any other thing you want. Once the animations has been completed it can update any changes from the domain as needed.

This allow you to focus on the games rules when working with the domain, as well as the artificial intelligence (if one exists) without considering animations. Then when you go to the view code you simply need to make animations for each of the actions. "Discard" would have one animation. "Draw new card" another. And so on.

This may not be the "best" example, but divide and conquer is a good strategy, reduce the problem into smaller problems and solve them one at a time.

---
Tags: architecture, gui
---


# Question
Title: Why would some PNG files extracted from games display incorrectly?
I've noticed extracting PNGs from some game files that the image becomes distorted part-way through. For example, here are a couple of PNGs extracted from the Textures file in Skyrim:

Is this some unusual variation on a PNG format? What modifications would I need to make to view such PNGs properly?

# Answer
> 22 votes
Here are the “restored” images, thanks to tillberg's further research:

As expected, there is a **5-byte block marker** every about 0x4020 bytes. The format appears to be the following:

```
struct marker {
    uint8_t tag;  /* 1 if this is the last marker in the file, 0 otherwise */
    uint16_t len; /* size of the following block (little-endian) */
    uint16_t notlen; /* 0xffff - len */
};

```

Once the marker has been read, the next `marker.len` bytes form a block that is part of the file. `marker.notlen` is a control variable such that `marker.len + marker.notlen == 0xffff`. The last block is such that `marker.tag == 1`.

The structure is probably as follows. There are still unknown values.

```
struct file {
    uint8_t name_len;    /* number of bytes in the filename */
                         /* (not sure whether it's uint8_t or uint16_t) */
    char name[name_len]; /* filename */
    uint32_t file_len;   /* size of the file (little endian) */
                         /* eg. "40 25 01 00" is 0x12540 bytes */
    uint16_t unknown;    /* maybe a checksum? */

    marker marker1;             /* first block marker (tag == 0) */
    uint8_t data1[marker1.len]; /* data of the first block */
    marker marker2;             /* second block marker (tag == 0) */
    uint8_t data2[marker2.len]; /* data of the second block */
    /* ... */
    marker lastmarker;                /* last block marker (tag == 1) */
    uint8_t lastdata[lastmarker.len]; /* data of the last block */

    uint32_t unknown2; /* end data? another checksum? */
};

```

I haven't figured out what is at the end, but since PNGs accept padding, it's not too dramatic. However, the encoded file size clearly indicates that the last 4 bytes should be ignored...

Since I did not have access to all block markers just before the beginning of the file, I wrote this decoder that starts at the end and attempts to find the block markers. It's not robust at all but well, it worked for your test images:

```
#include <stdio.h>
#include <string.h>

#define MAX_SIZE (1024 * 1024)
unsigned char buf[MAX_SIZE];

/* Usage: program infile.png outfile.png */
int main(int argc, char *argv[])
{
    size_t i, len, lastcheck;
    FILE *f = fopen(argv[1], "rb");
    len = fread(buf, 1, MAX_SIZE, f);
    fclose(f);

    /* Start from the end and check validity */
    lastcheck = len;
    for (i = len - 5; i-- > 0; )
    {
        size_t off = buf[i + 2] * 256 + buf[i + 1];
        size_t notoff = buf[i + 4] * 256 + buf[i + 3];
        if (buf[i] >= 2 || off + notoff != 0xffff)
            continue;
        else if (buf[i] == 1 && lastcheck != len)
            continue;
        else if (buf[i] == 0 && i + off + 5 != lastcheck)
            continue;
        lastcheck = i;
        memmove(buf + i, buf + i + 5, len - i - 5);
        len -= 5;
        i -= 5;
    }

    f = fopen(argv[2], "wb+");
    fwrite(buf, 1, len, f);
    fclose(f);

    return 0;
}

```

### Older research

This is what you get when removing byte `0x4022` from the second image, then by removing byte `0x8092`:

It doesn’t really “repair” the images; I did this by trial and error. However, what it tells is that there is unexpected data every 16384 bytes. My guess is that the images are packed in some kind of filesystem structure and the unexpected data is simply **block markers** that you should remove when reading the data.

I don’t know where exactly the block markers are and their size, but the block size itself is most certainly 2^14 bytes.

It would help if you could also provide a hex dump (a few dozen bytes) of what appears right before the image and right after. This would give hints about what kind of information is stored at the beginning or end of the blocks.

Of course there’s also the possibility that there is a bug in your extraction code. If you are using a buffer of 16384 bytes for your file operations, then I would first check there.

# Answer
> 18 votes
Based on Sam's suggestion, I forked James' code at https://github.com/tillberg/skyrim and was able to successfully extract n\_letter.png from the Skyrim Textures BSA file.

The "file\_size" given by the BSA headers is not the actual final file size. It includes some header info as well as some random chunks of useless-seeming data scattered around.

The headers look something like this:

* 1 byte (length of file path?)
* the full path of the file, one byte per character
* 12 bytes of unknown origin, as James posted (40 25 01 00 78 9c 00 2a 40 d5 bf).

To strip off the header bytes, I did this:

```
f.seek(file_offset)
data = f.read(file_size)
header_size = 1 + len(folder_path) + len(filename) + 12
d = data[header_size:]

```

From there, the actual PNG file starts out. It's easy to verify that from the PNG 8-byte start sequence.

I proceeded to try to figure out where the extra bytes were located by reading the PNG headers and comparing the length passed in the IDAT chunk to the implied data length inferred from measuring the number of bytes until the IEND chunk. (for details on that, check out the bsa.py file at github)

The sizes given by the chunks in n\_letter.png are:

```
IHDR: 13 bytes
pHYs: 9 bytes
iCCP: 2639 bytes
cHRM: 32 bytes
IDAT: 60625 bytes
IEND: 0 bytes

```

When I measured the actual distance between the IDAT chunk and the IEND chunk after it (by counting bytes using string.find() in Python), I found that the actual IDAT length implied was 60640 bytes - there were an extra 15 bytes in there.

In general, most of the "letter" files had an extra 5 bytes present for every 16KB of total file size. For example, o\_letter.png, at around 73KB, had an extra 20 bytes. Larger files, like the arcane scribblings, mostly followed the same pattern, though some had odd amounts added on (52 bytes, 12 bytes, or 32 bytes). No idea what's going on there.

For the n\_letter.png file, I was able to find the correct offsets (mostly by trial and error) at which to remove the 5-byte segments.

```
index = 0x403b
index2 = 0x8070
index3 = 0xc0a0
pngdata = (
  d[0      : (index - 5)] +
  d[index  : (index2 - 5)] +
  d[index2 : (index3 - 5)] +
  d[index3 : ] )
pngfile.write(pngdata)

```

The five byte segments removed are:

```
at 000000: 00 2A 40 D5 BF (<-- included at end of 12 bytes above)
at 00403B: 00 30 40 CF BF
at 008070: 00 2B 40 D4 BF
at 00C0A0: 01 15 37 EA C8

```

For what it's worth, I've included the last five bytes of the unknown 12-byte segment because of some similarity with the other sequences.

It turns out they're not quite every 16KB, but at ~0x4030 byte intervals.

To guard against getting close-but-not-perfect matches in the indices above, I also tested zlib decompression of the IDAT chunk from the resulting PNG, and it passes.

# Answer
> 3 votes
Actually, the intermittant 5 bytes are part of the zlib compression.

As detailed on http://drj11.wordpress.com/2007/11/20/a-use-for-uncompressed-pngs/,

> 01 the little endian bit string 1 00 00000. 1 indicating the final block, 00 indicating a non-compressed block, and 00000 are 5 bits of padding to align the start of a block to on octet (which is required for non-compressed blocks, and very convenient for me). 05 00 fa ff The number of octets of data in the uncompressed block (5). Stored as a little-endian 16-bit integer followed by its 1′s complement (!).

.. so a 00 indicates a 'next' block (not an ending one), and the 4 next bytes are the block length and its inverse.

\[Edit\] A more reliable source is of course RFC 1951 (Deflate Compressed Data Format Specification), section 3.2.4.

# Answer
> 1 votes
Is it possible that you're reading the data from the file in a text mode (where line endings that happen to appear in the PNG data are possibly mangled) instead of in a binary mode?

---
Tags: file-format, image
---


# Question
Title: How much would it cost to hire a musician
I've been building a game in RPG Maker XP, the music i use are either from the RTP::Standard that comes shipped with it, edits of the RTP after i convert the MIDI to a different format or from Game/Movie/Anime Soundtracks that i've brought

i kinda want to have my own music, my own identifiable theme to the game (and subsequently series), thing is, all the tunes i come up with are in my head, i've tried trying to make them but i got very little to no skills, the best i do is pitch changes and knowing where to cut and paste to make seamless tracks sometimes.

a rough estimate i came up with is $52,000, $1,000 a week, that's what i see as a minimal wage but i don't know how musician (or those who specialize in video game music) get paid, if it time based or per-piece based

NOTE: while i'm a perfectionist and like to have a much polish to the game when it's done to match my vision of it, it's not too important, i can make do with what i have as i will have the skills to get the game done

NOTE 2: yes this is much like another question i asked about about graphics, my forte is in programming and design....roughly

---

How my question is structured

Paragraph 1: my current situation

Paragraph 2: why i am asking this question

Paragraph 3: what knowledge i do have on the subject

NOTES: snippets of information that may not relate to the question but may help understand my position more

i thank MrKatSwordfish and redrazor11 for your help, you may not have given me a finite amount but you have revealed to me that there are numerous variables

i still remain hard on the fact this is a question and MrKatSwordfish and redrazor11 are legitimate answers though the constant editing and downing of my reputation has make released this question is more suited for a forum

# Answer
> 2 votes
You should probably find a musician online who's style that you like, and then contact them about commissioning a certain amount of minutes/songs.

With freelance artists and musicians, unless they work with you in a studio setting, it's very difficult to work out hourly/weekly payment methods. Going down that road may lead to potential issues/disputes later. It's a much better idea to pay them for 'x' minutes of finished music, or 'x' number of completed tracks.

Another important thing to consider is working out some kind of deal for an amount of revisions. This is important so that you can arrange to listen to the finished/nearly-finished tracks and have them adjusted or revised to your personal taste.

Please also make sure that both you and any musician/artist that you work together with have a very firm and clear understanding of the ownership plans. Are they making the music for you to use as you please, with a one-time fee? Just make sure that everyone is on the same page..

-- Also, when it comes down to the exact price, there really isn't a standard. It varies from person to person. I'd suggest this:

* Decide how many minutes of audio you want to have commissioned.
* Decide how many revisions you may need/ask them to do. Factor this into the contract/deal, make it very clear to both parties.
* Look around, and reach out to musicians.
* If possible, become familiar with the artist's previous work/portfolio. If it's not possible, try to ask for a sample of their work.
* If the artist is interested in working on the project, tell them that you would like ***_*\__** minutes of audio, with **_** *potential revisions, by* **\__** date. (You can try to suggest a price/minute of rendered audio, OR you can ask them how much they charge per minute of rendered audio.

In short. Figure out specifically what you need in terms of audio-minutes, revisions, fileformats (midi? audio?), time, etc. When you've figured out what exactly you need, and when you need it, contact various musicians that you like, and find out if they are willing/able to provide commissioned service under these terms.

Good luck! :D

# Answer
> 0 votes
Depending on your "musical vision" for the theme song, you could probably contract a freelance musician into creating a song for you. Look on something like oDesk or the like. I'm not saying you're going to get symphony style composition and production, but it's a start.

Make sure to get legalities straight too, because if your game become the next big thing, it could spell trouble.

---
Tags: music, costs
---


# Question
Title: Desktop twist, does anyone know how to implement this effect in DirectX?
http://my.tv.sohu.com/u/vw/26933139

I didn't know what the exactly name for this effect, so I just paste the link of the video here, I want to know what is the knowledge background needed if I want to create such a effect?

# Answer
The twisting/distorting effect can be done by making a triangle mesh that is initially a rectangle covering the screen, but with a fair amount of subdivision. Then you let the user alter the shape by clicking and dragging. One way to do that is by soft selection: when they click, you find all the verts within a certain distance of the pointer and compute weights that vary smoothly from 1.0 at the pointer to zero at the outside of the radius; then you adjust the positions of the points by weight * the drag vector. Another way to do it might be with a soft-body physics model, although that's a lot trickier.

You apply an image to it by simply putting a texture on the mesh. How they get the Windows desktop to be the texture I don't know. It's pretty easy to get a static screenshot of the desktop as your program starts up, and use that as a texture, but that wouldn't let you interact with it and get an updated render. In Vista/Win7 with the DWM it *might* be possible to get it to let you look at the composited desktop render target. However in the video it looks like Windows XP. I suspect there might actually be two computers running, one "slave" that displays the desktop normally, and one "master" that captures the slave's video signal and uses that as a texture in the distortion program. That's just a guess, though.
> 3 votes

---
Tags: graphics, directx
---


# Question
Title: Check if the vector is behind another or maybe opposite directions?
I'm doing a network game and on the client side, i interpolate the client position with the server sent extrapolated position. The client has its own physics simulation wich is corrected by the server in steps. The problem is when it laggs and i 'kick' the ball, the server gets a delayed message and sends me the position backwards of the client position wich makes the ball goes back and forth. I want to ignore those and maybe compensate that on the server, not sure though. The problem is the clock difference on those case are 0.07ms or 0.10 ms wich isn't that high to ignore the message i guess.

When i get the server position, i extrapolate with the clock interval * serverBallVelocity

Can i check if my new ball server position is behind my actual ball vector position? I tried to use the dot product after normalized the two vectors to check if they are opposite but it ain't working properly.

Any suggestions on checking that?

# Answer
> 5 votes
So you have a problem of the kind: *Is a point BS in front or behind a plane defined by a point BC and a normal vector N?*

* **BS** is the ball position as seen by the server
* **BC** is the ball position as seen by the client
* **N** is the vector which points exactly to the "front" of the ball position (usually, this will be your camera's viewing direction or a character's front direction).

Consequently, the vector , pointing from the client's to the server's ball position, will point roughly in the same direction as N if the ball position of the server is in front of the plane, and in the other direction if it's behind it. As such, the dot product of those two - - will be positive if BS is in front of BC, negative if it's behind, and around zero if it's to the side.

The calculation is then simple, in pseudo-C, and assuming three Euclidean dimensions:

```
bool is_in_front(vector3 ball_server,
                 vector3 ball_client,
                 vector3 front_direction)
{
    double product = (ball_server.x - ball_client.x) * front_direction.x
                     + (ball_server.y - ball_client.y) * front_direction.y
                     + (ball_server.z - ball_client.z) * front_direction.z;
    return (product > 0.0);
}

```

# Answer
> 4 votes
**This is a good example of a situation you're asking for an answer to the wrong question.**

You don't want to detect if the incoming vector is behind your ball. It will *always* be behind your ball, since there is always lag between your server and client.

The correct solution is to measure the round trip time between client and server and to adjust accordingly. If you know that you have a latency of 40ms, the ball is moving at velocity (1,-1), and you want to tell the client that the ball will be at (4,7) right now, you want to send the the position as (4.04, 6.96).

That way, when the client receives the update 40ms later, it will set the position to (1,-1) * 40ms away from where the ball was when the server sent the message, which is exactly where it should be.

You'll also want to do smoothing and interpolation, rather than teleporting the ball to the requested position.

# Answer
> 0 votes
As a real life example, I wanted to see if my player was allowed to attack a zombie with a weapon.

The zombie had to be in front of the player...

```
var playerDirection:Vector2 = VectorUtility.createFromAngle(
        worldState.playerLocation.radians);
var dot:Number = VectorUtility.dotProduct(worldState.delta, playerDirection);
var isInfrontofPlayer:Boolean = dot <= -.8;

```

I decided to check for -.8 as I did not want the player to attack a zombie who is on the sides of the player.

---
Tags: networking, vector
---


# Question
Title: Is a recursive game object update better than a linear one?
I have a tree of gameobjects, so every node contains a list of children. In update function: Is it better to do recursive or linear walking through game objects.

```

update() {
    update self;
    foreach child call update;//recursive call
}

```

or

```

array of children = root.getAllChildrenRecursive
foreach child in array of children call update; //linear walking through gameobjects.

```

# Answer
> 8 votes
If you only have a few gameobjects it doesn't really matter. But if you are planning support for lots of gameobjects, I suggest you take at look at the following question:

Game engine and data driven design

And continue to read the following article (originally printed in Game Developer):

Data-Oriented Design (Or Why You Might Be Shooting Yourself in The Foot With OOP)

Another thing you should consider is if your scene hierarchy is the most efficient/flexible/maintainable. I suggest you read the following blog about component based game engine:

Evolve Your Hierarchy

And maybe continue reading this excellent Q/A:

Component based game engine design

... but before you start on spending a huge amount of time trying to create the perfect game engine remember that "premature optimization is the root of all evil". Always use a profiler to see where the bottle neck is in your game / game engine.

# Answer
> 5 votes
IMHO: If you are programming some real-time application, you should avoid recursion if it's possible. Recursion has to push and pull curent context and it's slowing down your app. It's also more memory complex.

Of course if you have just few objects, it's not so dramatic. But when you will add more and more objects in future, it will be slower and slower.

You can read something about it in this article on wikipedia.

# Answer
> 5 votes
Recursion and depth-first traversal are not the same thing.

This is also not about the merits of scene graph versus lists of components or whatever. It's also more of a general computer science issue than it is a gamedev issue.

Bummzack's comment about how wasteful it is to create a whole new list is extremely important. You need to traverse your tree in-place where it sits, not pull some list out of it as though it were a database. There are two general methods for doing this: recursion and iteration.

In general, iterative is faster than recursive unless you are working in a language with tail call optimization, but you should still write code in the most intuitive way possible. If you're dealing with a tree of objects, often the most intuitive approach for traversal is a recursive solution.

*However*, be sure to mark this as a potential trouble spot, (ie: `// TODO PERFORMANCE Keep an eye on performance for this traversal`). If you find it's slowing the game down, consider changing to an iterative traversal method.

It's about something like this:

```
void ProcessTree(Node root)
{
    PreProcess(root);
    foreach (var child in root.children) {
        ProcessTree(child);
    }
    PostProcess(root);
}

```

versus something like this:

```
void ProcessTree(Node root)
{
    Stack<Node> traversalStack = new Stack<Node>();
    traversalStack.push(root);
    while (!traversalStack.isEmpty {
        var current = traversalStack.peek();
        if (!current.preProcessedAlready) {
            PreProcess(current);
        }

        if (current.hasChild) {
            current = current.firstChild;
            traversalStack.push(current);
            continue;
        } else if (current.hasSibling) {
            PostProcess(current);
            traversalStack.pop()
            current = current.nextSibling;
            traversalStack.push(current);
            continue;
        } else {
            PostProcess(current);
            traversalStack.pop();
            current = traversalStack.pop();
            while (!traversalStack.isEmpty) {
                if (current.hasNextSibling) {
                    traversalStack.push(current.nextSibling)
                    break;
                } else {
                    current = traversalStack.pop();
                    PostProcess(current);
                }
            }
        }
    }
}

```

The difference is you keep allocating a whole new stack frame for visitation, versus just adding a small stack node, which you can cache by pooling the stack nodes or just figuring out the maximum depth of your tree.

I'm pretty sure I screwed up the iterative example logically and in terms of efficient code flow, so please edit/comment with fixes. Wikipedia has a good article on tree traversal for better examples (most seem to be binary trees unfortunately). There's also a way to avoid using a stack if you maintain some extra pointers in the Node object as per this StackOverflow answer.

Do the easy thing (recursion, or occasionally iteration, depending on the problem) first and build something more robust or performant as you need it, but also don't 100% depend on your method, be willing and able to switch if it's called for. I ran into this issue on Unity recently. Our tree by necessity had much more depth than breadth, so the iterative method cut out 4 seconds of loading time (*for **our** data and **our** processing,* ***NOT A BENCHMARK***) compared to recursive.

# Answer
> 2 votes
Go with linear, as it's easier to follow and iterate through objects than it does adding more to a stack and unwind. If the order in which the gameobjects are updated is not very crucial to the behavior and interaction between, linearly updating would be all you'd need. It all depends on how strongly coupled the objects' behaviors are on each other.

---
Tags: algorithm, optimization
---


# Question
Title: Should I use reference counting on entities in component-based entity system?
In component-based entity system, should game objects be **reference counted**? What about components? Tell me please your pro and contra.

# Answer
> 0 votes
I have a lot of minuses on this question, but I tried to use reference counting on my entities and components, and now I like this approach very very much. So if someone is interested, I stopped on using reference counting on these objects. I used this approach a bit and see now a lot of benefits and hope in future there won't be problems.

---
Tags: architecture, memory
---


# Question
Title: How to make an Alert Dialog "Rate my game" for my game
I wonder if anyone can help me on how to make an alert dialog which makes user rate the game from inside the game itself or taking the user to google play to rate. Please help. I'm using andengine.

# Answer
> 2 votes
I think this may be what you are looking for. It shouldn't matter that you are using andengine. Its all the same =-)

http://www.androidsnippets.com/prompt-engaged-users-to-rate-your-app-in-the-android-market-appirater.html

---
Tags: andengine
---


# Question
Title: Negative timeout value in Variable Timestep loop
I was working on my game loop and I came across an odd problem. The loop was working fine, my states could render, received updates, etc. I then proceeded to create my Input system, which, also works. However, after implementing that I continually & randomly receive a Exception in my thread stating: *Exception in thread "Thread-3" java.lang.IllegalArgumentException: timeout value is negative*

I first tried to debug this. The problem is there is 0 consistency with the exception occurring. KeyEvents *seem* to have no affect, due to the fact I can use the poll system & not generate an exception. That & sometimes upon running it automatically throws an exception. I've re-looked through the code and I'm not quite sure what is causing this.

For convenience I'll just leave the relevant code.

```
public class Game implements Runnable {

public int FPS = 0;

private Double delta;
private long lastFps = 0;

private final int TARGET = 60;
private final long OPTIMAL_TIME = 1000000000 / TARGET;
private boolean gameRunning = false;

@Override
public void run() {

    long lastLoop = System.nanoTime();

    while (gameRunning){

        //Figure out how long its been since last update - used for entity calculation
        long current = System.nanoTime();
        long updateTime = current - lastLoop;
        lastLoop = current;

        delta = updateTime / ((double)OPTIMAL_TIME);

        lastFps += updateTime;
        FPS++;

        if(lastFps >= 1000000000){
            System.out.println("(FPS: "+ FPS +")");
            lastFps = 0;
            FPS = 0;
        }

        //Updates state + calls render
        updateState();

        /*
         * We need each frame to take 10mill-sec
         * Take recorded time + 10 milli
         * then factor current time
         * this ^ is final value to wait
         */
        try{
            Thread.sleep( (lastLoop - System.nanoTime() + OPTIMAL_TIME) /1000000 );
        }
        catch(InterruptedException exception){
            exception.printStackTrace();
        }

    }

}

```

Unless the KeyEvent's could possibly have relation to the problem or my input polling (Which doesn't manage time or anything affecting the thread) I'm not sure if it's needed to post any relevant code from that class. (If you think I need to you're welcome to ask but it's just boolean arrays + a string cache).

**The question:** Why is the thread encountering a negative timeout value?

# Answer
> 1 votes
Your problem is in the line that performs the sleep operation:

```
Thread.sleep( (lastLoop - System.nanoTime() + OPTIMAL_TIME) /1000000 );

```

Remember that System.nanoTime() will almost *always* be after the last-recorded time stored in lastLoop, so you need to reverse those two expressions.

# Answer
> 1 votes
Okay fixed the problem. As suggested by a friend + comment I should be using MicroTime which has appeared to solve the problem. For anyone looking for how I solved it, I just changed these 2 lines to this:

```
long current = System.currentTimeMillis();

Thread.sleep( (lastLoop - System.currentTimeMillis() + OPTIMAL_TIME) /1000000 );

```

---
Tags: java, game-loop
---


title: DirectX UV Coordinates not responding?

text:
# Question
Title: DirectX UV Coordinates not responding?
My UV coordinates never respond to me for some reason. It is just UV mapping itself in the smallest way possible. It's a tile-able texture and the program is subdividing so much I can't even zoom in and see it right. It just looks like lots of noise. So I set my UV coordinates to 0 and 0 for every vertex and it ignored and mapped the same way still. I continuously just changed the coordinates and I'm not getting any results.

Shader: http://gyazo.com/0422d4f37134671eb0b35c2a00605f7e

Declaration:

```
    D3DVERTEXELEMENT9 Decl[] =
    {
        {
            0,
            0,
            D3DDECLTYPE_FLOAT3,
            D3DDECLMETHOD_DEFAULT,
            D3DDECLUSAGE_POSITION,
            0
        },
        {
            0,
            0,
            D3DDECLTYPE_FLOAT2,
            D3DDECLMETHOD_DEFAULT,
            D3DDECLUSAGE_TEXCOORD,
            0
        },
        D3DDECL_END()
    };

```

My Vertice UV:

```
                Vertices[y * WIDTH + x].V = y / 1.28;
                Vertices[y * WIDTH + x].U = x / 1.28;

```

My struct:

```
struct CUSTOMVERTEX
{
    float X, Y, Z;
    float U, V;
};

```

# Answer
I found the issue. The simple solution was changing the declaration in the TEXCOORD area I made it

```
         {
            0,
            sizeof(float) * 3,
            D3DDECLTYPE_FLOAT2,
            D3DDECLMETHOD_DEFAULT,
            D3DDECLUSAGE_TEXCOORD,
            0
        },

```
> 0 votes

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


# Question
Title: XNA How to detect collision between 2d sprites and 3d primitives (not models)
**My current status**

I have already read some tutorials about 3d collision. I know how ray trace works and how to convert mouse follow a vector to track the closest object that collides with out vector I have also worked with 2d collisions before and I've seen some collision samples from "apphub".

**My Problem**

My problem is mainly because all the tutorials I have read are about collisions over 3d models on .fbx format but I don't use model files... I use simple primitives... So what methods do I need to check to be able to know if a 2d sprite has collided with my 3d isometric triangle? Also bounding box will have blank spaces outside my triangle borders that will return a false positive.

**Main Questions**

1. Is there a way to transform primitive into 3d models so i can use Ray.Intersect?
2. Do I need to transform the vertices into 2d points and then check if any pixel from sprite is between these 3 lines?
3. I'm also aware of boundingbox but it doesnt seems to be a good solution since we are talking about a triangle not a square. Or should I create a bounding box around the 2d sprite and then try to collide over all the Z's?

If you need clarification please let me know. I'm not very good in explaining myself.

thanks

# Answer
> 0 votes
I tried using the bounding box but as I suspected this method lacks of precision to be used with triangles.

So what I did was... instead using a bounding box I choose doing the collision in 2d. I used Viewport.unproject to convert the vertices from the triangle which was generated in 3d world and then instead using the whole 2d sprite I picked a point in the center of the sprite.

After some research I chosen to use this method to improve the collision to triangle.

http://www.gamespp.com/algorithms/CollisionDetectionTutorial.html

This algorithm connects a chosen point to all the vertices and it creates vectors. Then it tries to sum the angle made by the pair of each vertices. If the sum of the angles is 360 then the point is inside the triangle.

The samples in apphub for 3d collision use another algorithm developed by Tomas Moller and Ben Trumbore http://www.graphics.cornell.edu/pubs/1997/MT97.html

# Answer
> 1 votes
Why not making a BoundingBox and/or Triangle with the 2D volume being with the Z dimension at 0? Then use XNAs built in intersects methods.

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


title: UIView with IrrlichtScene

text:
# Question
Title: UIView with IrrlichtScene
i have a UIViewController in a Storyboard and want to draw a IrrlichtScene in this View Controller.

My Code:

# WWSViewController.h

```
#import <UIKit/UIKit.h>

@interface WWSViewController : UIViewController {
    IBOutlet UILabel *errorLabel;
}

@end

```

# WWSViewController.mm

```
#import "WWSViewController.h"
#include "../../ressources/irrlicht/include/irrlicht.h"

using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;

@interface WWSViewController ()

@end

@implementation WWSViewController

-(void)awakeFromNib {
    errorLabel = [[UILabel alloc] init];
    errorLabel.text = @"";

    IrrlichtDevice *device =
    createDevice( video::EDT_OGLES1, dimension2d<u32>(640, 480), 16,
                 false, false, false, 0);

    /*
     Set the caption of the window to some nice text. Note that there is an
     'L' in front of the string. The Irrlicht Engine uses wide character
     strings when displaying text.
     */
    device->setWindowCaption(L"Hello World! - Irrlicht Engine Demo");

    /*
     Get a pointer to the VideoDriver, the SceneManager and the graphical
     user interface environment, so that we do not always have to write
     device->getVideoDriver(), device->getSceneManager(), or
     device->getGUIEnvironment().
     */
    IVideoDriver* driver = device->getVideoDriver();
    ISceneManager* smgr = device->getSceneManager();
    IGUIEnvironment* guienv = device->getGUIEnvironment();

    /*
     We add a hello world label to the window, using the GUI environment.
     The text is placed at the position (10,10) as top left corner and
     (260,22) as lower right corner.
     */
    guienv->addStaticText(L"Hello World! This is the Irrlicht Software renderer!",
                          rect<s32>(10,10,260,22), true);

    /*
     To show something interesting, we load a Quake 2 model and display it.
     We only have to get the Mesh from the Scene Manager with getMesh() and add
     a SceneNode to display the mesh with addAnimatedMeshSceneNode(). We
     check the return value of getMesh() to become aware of loading problems
     and other errors.

     Instead of writing the filename sydney.md2, it would also be possible
     to load a Maya object file (.obj), a complete Quake3 map (.bsp) or any
     other supported file format. By the way, that cool Quake 2 model
     called sydney was modelled by Brian Collins.
     */
    IAnimatedMesh* mesh = smgr->getMesh("/Users/dbocksteger/Desktop/test/media/sydney.md2");
    if (!mesh)
    {
        device->drop();

        if (!errorLabel) {
            errorLabel = [[UILabel alloc] init];
        }
        errorLabel.text = @"Konnte Mesh nicht laden.";
        return;
    }
    IAnimatedMeshSceneNode* node = smgr->addAnimatedMeshSceneNode( mesh );

    /*
     To let the mesh look a little bit nicer, we change its material. We
     disable lighting because we do not have a dynamic light in here, and
     the mesh would be totally black otherwise. Then we set the frame loop,
     such that the predefined STAND animation is used. And last, we apply a
     texture to the mesh. Without it the mesh would be drawn using only a
     color.
     */
    if (node)
    {
        node->setMaterialFlag(EMF_LIGHTING, false);
        node->setMD2Animation(scene::EMAT_STAND);
        node->setMaterialTexture( 0, driver->getTexture("/Users/dbocksteger/Desktop/test/media/sydney.bmp") );
    }

    /*
     To look at the mesh, we place a camera into 3d space at the position
     (0, 30, -40). The camera looks from there to (0,5,0), which is
     approximately the place where our md2 model is.
     */
    smgr->addCameraSceneNode(0, vector3df(0,30,-40), vector3df(0,5,0));

    /*
     Ok, now we have set up the scene, lets draw everything: We run the
     device in a while() loop, until the device does not want to run any
     more. This would be when the user closes the window or presses ALT+F4
     (or whatever keycode closes a window).
     */
    while(device->run())
    {
        /*
         Anything can be drawn between a beginScene() and an endScene()
         call. The beginScene() call clears the screen with a color and
         the depth buffer, if desired. Then we let the Scene Manager and
         the GUI Environment draw their content. With the endScene()
         call everything is presented on the screen.
         */
        driver->beginScene(true, true, SColor(255,100,101,140));

        smgr->drawAll();
        guienv->drawAll();

        driver->endScene();
    }

    /*
     After we are done with the render loop, we have to delete the Irrlicht
     Device created before with createDevice(). In the Irrlicht Engine, you
     have to delete all objects you created with a method or function which
     starts with 'create'. The object is simply deleted by calling ->drop().
     See the documentation at irr::IReferenceCounted::drop() for more
     information.
     */
    device->drop();

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

```

Sadly the result is just a black View in the Simulator. :( Hope here is anyone who can explain me how i draw the scene in a UIView.

Furthermore I'm getting this Error:

> Could not load sprite bank because the file does not exist: #DefaultFont

How can i fix it ?

# Answer
Maybe in your

```
createDevice( video::EDT_OGLES1, ... )

```

is wrong **video::EDT\_OGLES1**. This is a OpenGL pointer?

If Yes, then try add this code lines after createDevice() :

```
self.view = video::EDT_OGLES1;

```

and add this WWSViewController to root viewcontroller how:

```
[mainViewController presentModalViewController: mWWSViewController animated: NO];

```

where **mWWSViewController** is pointer to your WWSViewController view controller
> 0 votes

---
Tags: ios, objective-c, fonts, irrlicht, view
---


title: OpenGL matrix vs DirectX matrix

text:
# Question
Title: OpenGL matrix vs DirectX matrix
I'm working on an animation and model exporter from Maya to use within my game. Currently, models work perfectly, and animations have some issues with the joints. Since Maya works in an OpenGL environment and my game works with DirectX, to load the mesh in I negated the Z component of all vertex positions, normals, and inverted the UV's V coordinate.

Currently, joints loaded in are reversed along the Z axis. My question is, what do I need to do to get bone matrices working properly from OpenGL to DirectX? My original thought was to just transpose them, but that doesn't work. I've also tried negating the z-column but that causes some odd stretching.

I've only been trying to invert the root bone.

Notice the feet joints pointing backward. https://i.stack.imgur.com/6kNr2.png

Inverting the root joints Z-Column, weird stretching and it looks like he's slouched. https://i.stack.imgur.com/KysH8.png

Any thoughts on this?

# Answer
> 0 votes
You need to flip your matrices and all points or use a Right handed projection matrix for everything in your game.

I wrote my own exporter and noticed the same problem but like Left handed so I just multiplied all Maya matrices by the following

```
// A float version of a right to left handed converison matrix
float RightToLeftMatData[4][4] = {
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, -1, 0,
    0, 0, 0, 1,
};

//Not sure why but transforms must be built off of the dagPath
MStatus status;
MMatrix tMMat = dagPath.inclusiveMatrix(&status);
if (status != MS::kSuccess)
    Error("Failed to get inclusive matrix");
tMMat.get(tMat.m);

// Cobalt always uses left handed coordinates so convert the coordinate system
if (ConvertFromRightHandedCoordinate)
{
    tMat = mRightToLeft * tMat * mRightToLeft;
}

```

Also you'll need to modify every vertex's position, normal, binormal, tangent, and bitangent like so...

```
//Animation requires that we do not get vertex points pretransformed to world space
fnMesh.getPoints( vertexList, MSpace::kObject);
for ( uint32 i = 0; i < vertexList.length(); i++ )
{
    vertexList[i].cartesianize();
    MPoint point = vertexList[i];
    if (ConvertFromRightHandedCoordinate) vPoint.push_back(cVector3(point.x, point.y, -point.z));
    else vPoint.push_back(cVector3(point.x, point.y, point.z));
}

fnMesh.getNormals( normalList, MSpace::kObject);
for (uint32 i = 0; i < normalList.length(); i++)
{
    MPoint point = normalList[i];
    if (ConvertFromRightHandedCoordinate) vNormal.push_back(cVector3(point.x, point.y, -point.z));
    else vNormal.push_back(cVector3(point.x, point.y, point.z));
}

```

// Same thing for binormal and bitangent

I also flip the V coordinates for textures though you could always do this in a shader if you'd prefer. A lot of shader examples from NVidia actually have a flag to do that.

If you need some reference material feel free to take anything you want from my maya conversion. http://code.google.com/p/cobaltlibrary/source/browse/trunk/Tools/Source/MayaConvert/MayaFile.cpp

# Answer
> 0 votes
I don't think you need to flip the z-coordinate of your vertex, just transpose you matrix and use it in your DirectX program A command misunderstanding about this is LH or RH system, but it's really nothing about which coordinate system you are using, it's about row-major(DirectX) or column-major(OpenGL) matrix.

---
Tags: opengl, mathematics, directx, animation, matrix
---


# Question
Title: Platforming - Hanging off of cliffs and edges?
> **Possible Duplicate:**
> Programming a climbing system like tomb raider

I've been interested in platforming gameplay dynamics for a while now. What I'm trying to ask is how games like Assassin's Creed, Prince of Persia, or any platformer do the environment interactions like hanging off of and climbing edges, etc. I have no idea how this kind of gameplay can be programmed.

In 3D games, the character is usually a capsule, so when the character falls off of a ledge and the grab onto it, where would the capsule be ? I'm confused... How the heck is this done ?

Thanks in advance.

# Answer
There is a LOT of hard work going into games like Assassin's Creed to make it work. The animation system and character animations are among the most complex (if not *the* most complex) in the industry.

I the general case, however, there are many different ways to solve this.

One is to add an additional hitbox to the character and one near ledges, test when those intersect, and then grab the edge info from the efge's hitbox.

Another is to simply use ray casting and test for collisions at roughly the height of the chafacters's arms while testing for a lack of collisions at the character's head height (L4D uses a system similar to this for making zombies climb things... Which is why you sometimes see them climb over light posts instead of simply running around them).

You could add a surface flag to walls below ledges and check when the players capsule collides with it. You could a plane extending from the ledge and check when the top of the player collides with that. You could attach ledges to navigation nodes and check for collision there.

A lot of this data and be automatically created by post-processing the level geometry (especially low or mid LOD levels). It can also be produced manually if designers are worried about players being able to climb willy nilly over any obstacles.

The hard part is animating it all. You need relatively fancy animation blending to do it in 3D. Simpler 2D games after just directly switch to a grab ledge frame of animation, but this requires more precise detection of when the character is in a position to grab a ledge.

In most cases I've seen, the hitbox around ledges approach is taken. If the player collides with one of them and is falling, he can grab the ledge. Some extra work to check that the collision is near the players hands and that the player is facing the ledge makes it feel an look better. Aside from that, te animation system has to be able to be given positions to attach the hands and to meld that with the existing falling ankmstion and the climbing animations.
> 1 votes

---
Tags: physics, game-mechanics, platformer
---


# Question
Title: Should I take line thickness into consideration for a grid based light game?
I'm currently rewriting some horrific code I wrote for a prototype and have stumbled right at the start! The game I'm working on revolves around directing light and there is a small ambiguity in regards to the way the grid is drawn:

Code wise, information about each node of the grid is stored in an `int[,]`, the grid lines are drawn for debugging purposes. Currently there is nothing explicitly defined for the line thickness, i.e if you look at the pixels closely, the bottom and right lines are drawn in a way which means the grid is not centered on screen, it is one pixel out!

If you shrink the scale of the grid to each being cell being 4x4 pixels the problem is really obvious:

The red area is the cell; the lines show how I draw the grid lines and what the light beams travels across. Would it better to represent this as a grid of 3x3 pixel cells with a line thickness of 1?

Normally I wouldn't be bothered too much because this is really looking into it in a lot of depth, but since the lines of light themselves actually traverse these currently non-existing lines I thought it might be better to make the representation a more elegant! What do you think?

# Answer
> 2 votes
Internally the game should handle the lines as zero-thickness. Thus the lines are between the grid cells. This applies to all logic and calculations of the game mechanism. When rendering, you need to decide how to adjust the lines to pixel based rendering. Usually the solution is to render the pixels that are bottom-right from the position of the logical line, just like you are currently rendering. One other option would be using antialiased lines with sub-pixel accuracy and render the line on both sides with 0.5 alpha, but this doesn't look as good when most lines are horizontal or vertical. If you are using the bottom-right rendering, you can enlarge the drawing canvas to bottom right by 1 pixel also to make the lines in the bottom and right edges visible as well.

It shouldn't really matter if you used 3x3 pixel cells with a grid between them, as this is only related to the rendering. It would just confuse the calculations.

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


title: Generate texture for a heightmap

text:
# Question
Title: Generate texture for a heightmap
I've recently been trying to blend multiple textures based on the height at different points in a heightmap. However i've been getting poor results. I decided to backtrack and just attempt to recreate one single texture from an SDL\_Surface (i'm using SDL) and just send that into opengl. I'll put my code for creating the texture and reading the colour values. It is a 24bit TGA i'm loading, and i've confirmed that the rest of my code works because i was able to send the surfaces pixels directly to my createTextureFromData function and it drew fine.

```
struct RGBColour
{
    RGBColour() : r(0), g(0), b(0) {}
    RGBColour(unsigned char red, unsigned char green, unsigned char blue) : r(red), g(green), b(blue) {}

    unsigned char r;
    unsigned char g;
    unsigned char b;
};

    // main loading code
SDLSurfaceReader* reader = new SDLSurfaceReader(m_renderer);
reader->readSurface("images/grass.tga");

// new texture
unsigned char* newTexture = new unsigned char[reader->m_surface->w * reader->m_surface->h * 3 * reader->m_surface->w];

for (int y = 0; y < reader->m_surface->h; y++)
{
    for (int x = 0; x < reader->m_surface->w; x += 3)
    {
        int index = (y * reader->m_surface->w) + x;

        RGBColour colour = reader->getColourAt(x, y);

        newTexture[index] = colour.r;
        newTexture[index + 1] = colour.g;
        newTexture[index + 2] = colour.b;
    }
}

unsigned int id = m_renderer->createTextureFromData(newTexture, reader->m_surface->w, reader->m_surface->h, RGB);

    // functions for reading pixels
RGBColour SDLSurfaceReader::getColourAt(int x, int y)
{
    Uint32 pixel;
    Uint8 red, green, blue;
    RGBColour rgb;

    pixel = getPixel(m_surface, x, y);

    SDL_LockSurface(m_surface);

    SDL_GetRGB(pixel, m_surface->format, &red, &green, &blue);

    SDL_UnlockSurface(m_surface);

    rgb.r = red;
    rgb.b = blue;
    rgb.g = green;

    return rgb;
}

    // this function taken from SDL documentation
// http://www.libsdl.org/cgi/docwiki.cgi/Introduction_to_SDL_Video#getpixel
Uint32 SDLSurfaceReader::getPixel(SDL_Surface* surface, int x, int y)
{
    int bpp = m_surface->format->BytesPerPixel;

    Uint8 *p = (Uint8*)m_surface->pixels + y * m_surface->pitch + x * bpp;

    switch (bpp)
    {
    case 1:
        return *p;
    case 2:
        return *(Uint16*)p;
    case 3:
        if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
            return p[0] << 16 | p[1] << 8 | p[2];
        else
            return p[0] | p[1] << 8 | p[2] << 16;
    case 4:
        return *(Uint32*)p;
    default:
        return 0;
    }
}

```

I've been stumped at this, and I need help badly! Thanks so much for any advice.

# Answer
> 1 votes
First, the size of your newTexture\[\] array looks suspicious; why is the extra factor of "reader-\>m\_surface-\>w" on the end? "width * height * 3" should be sufficient. That shouldn't affect correctness, but it's a big waste of memory.

More importantly, the indexing on your inner for loop doesn't look quite right. You need to be consistent about which variables are counting pixels vs. which are counting bytes. The "x" and "y" variables should be counting pixels, since that's what the getColourAt() function expects. But your inner for loop is incrementing x by 3 each time, which means you're only reading the color of every third pixel. Replace "x += 3" with "x++" and you'll hit every pixel.

The "index" variable is being used as a byte index into the newTexture\[\] array. After applying the above fix, "x" and "y" are pixel indices, so the byte index of pixel \[x,y\] would be given by "(y * reader-\>m\_surface-\>w + x) * 3".

---
Tags: c++, textures, sdl, heightmap
---


# Question
Title: Floating Point Precision (fp:precise vs. fp:fast)
**In C or C++, does the compiler option of floating point precision really make a difference in real world (small/indie) games?**

From my observations, setting fp:fast is many times faster than fp:precise and from what I understand here ( https://stackoverflow.com/questions/6889522/fpfast-vs-fpprecise-what-kind-of-errors-can-i-encounter ) the precision difference between the two compiler options only changes from the 16th digit of a floating point number.

Has anyone encountered an example when using fp:fast went terribly wrong for 2D or 3D games?

Edit: To clarify, I am not asking about the precision of floating point values themselves (ie. float vs double vs decimal). Only about precision related to the compiler option.

# Answer
> 13 votes
Your interpretation of fp:fast vs fp:precise sounds suspicious; I'm sure there's more of an effect than just rounding error after the 16th decimal place. I refer you to Bruce Dawson's article on floating point precision for more details.

In general, floating-point precision error is *definitely* a real problem in game development. It's especially troublesome for physics programmers and for games with large worlds or long running times (on the order of weeks or months, like an MMO). Floating point precision errors most often manifest as simulation instability and jittery movement that gradually gets worse over time. If you're not seeing those sorts of artifacts in your game, and the performance increase is significant, then it should definitely be safe to stick with fp:fast.

---
Tags: c++, c, floating-point
---


# Question
Title: Bullet impact or force on cube in Blender
Hoping someone here may be able to help. I'm new to Blender (and game development/3d modelling) and have been following some tutorials online to get me started. I am building a very basic FPS just to get started. I have a gun that shoots a cube object as a bullet, but when I shoot a different cube object that I added as a target, I have a number of issues. EDIT: The target cube is just set as a rigid body object. No other attributes as yet.

1. The cube only moves when I hit one particular face of the cube with a bullet. Otherwise, it doesn't register a hit. It's like the bullet passes right through it unless I hit the particular face.
2. When I hit the correct face, the cube flies way off the screen. I know this is controlled by the physics of each object but I can't find any explanations of it. It's like the box has no weight. If I increase the mass of it, walking against the cube is affected. The cube moves around slower/faster depending on the mass, but shooting it shows no change.

Could someone give a newbie some pointers?? Thanks so much guys.

btw I'm using Blender 2.6 but I reckon that's irrelevant really

# Answer
A couple thoughts: How heavy is the bullet you are firing? How fast is the bullet moving?

**Edit:** I'll expand on why I ask these. If the objects are the same mass, when one collides with the other, most of the velocity of the bullet will be transferred to the box. (in my comment I said energy instead of velocity, but the result velocity of each object depends on the relative masses during their collision)

You might take a look here: http://en.wikipedia.org/wiki/Kinetic\_energy

One more: On one of my projects, I noticed that an object, when moving too quickly, would fall into another. I fixed this by tweaking the physics step settings under the World tab.
> 1 votes

---
Tags: collision-detection, physics, blender
---


title: Scene graph in Unity3D

text:
# Question
Title: Scene graph in Unity3D
I was wondering if any scene graph-like mechanism is implemented into Unity3D? For example if I have a GameObject, can I add child cubes to it so when I rotate the parent GameObject, the siblings will rotate too?

# Answer
Yes, Transform component has Parent Transform. http://docs.unity3d.com/Documentation/ScriptReference/Transform-parent.html
> 6 votes

---
Tags: unity, rotation, scene-graph
---


# Question
Title: Dealing with alpha for 2D per pixel lighting
Right now I've got a simple light shader. Every bitmap I draw goes through it to make up the scene. I only draw quads.

```
   texture tex;
   sampler2D s = sampler_state {
      texture = <tex>;
   };

bool use_tex;

float x = 0.1;
float y = 0.3;

   float4 ps_main(VS_OUTPUT Input) : COLOR0
   {
float4 p = Input.vPosition / Input.vPosition.w;
      float4 color = 0;
      float a = color.a;
      if(!use_tex)
        {
           color = Input.Color;
        }
        else
        {
           color = Input.Color * tex2D(s, Input.TexCoord.xy);
        }
      p += 1.0;
      p /= 2;
      p.y = 1.0 - p.y;

      float3 lightAttenuation = float3(0.05,4.0, 0.0);
     // float4 color = Input.Color * tex2D(s, Input.TexCoord.xy);
      float2 aux = float2(x,y) - p.xy;
      float dist = length(aux);
      float attenuation=1.0/(lightAttenuation.x+lightAttenuation.y*dist

+lightAttenuation.z*dist*dist);

      float3 lightAttenuation2 = float3(0.05,3.0, 0.0);
      float2 aux2 = float2(0.5,0.4) - p.xy;
      float dist2 = length(aux2);
      float attenuation2=1.0/(lightAttenuation2.x

+lightAttenuation2.y*dist2+lightAttenuation2.z*dist2*dist2);

      color = (float4(attenuation,attenuation,attenuation,1.0) * color * float4(1.0,0.8,0.8,1.0)

* 0.8)  + (float4(attenuation2,attenuation2,attenuation2,1.0) * color * float4(1.0,0.8,1.0,1.0)

* 0.2);

      return color;
   }

```

The shader calculates based on the current pixel's screen position.

The problem is when the pixel's alpha is != 1.0

It this case it would need to be multiplied by what is already in the backbuffer at that pixel location in order to get the correct final pixel.

What can I do to fix the alpha issue and deal with the alpha case?

Thanks

PS2.0 hlsl.

Edit

Here are 2 images, the bright one is when the whole scene is rendered to texture then the shader is applied. The second is when I apply the shader on each fragment as the scene is rendered. This is an area where there is a dark shadow on the ground. The shadow is a semi transparent bitmap. Thus it makes the lighting effect weaker and it makes it look weird.

What I want is a way for it to look like the first one, but still letting me do per fragment shading. What I was saying was that I thought of maybe looking at what is already in the backbuffer, then multiplying it by the current pixel, then taking that result, applying the shader to it, then obviously you set the alpha to 1.0.

Im not sure if or how that could work. Im wondering either how to do that, or a better way to get the same result.

```
Here is my shader source:

   texture tex;
   sampler2D s = sampler_state {
      texture = <tex>;
   };

bool use_tex;

float x = 0.1;
float y = 0.3;

   float4 ps_main(VS_OUTPUT Input) : COLOR0
   {
float4 p = Input.vPosition / Input.vPosition.w;
      float4 color = 0;

      if(!use_tex)
        {
           color = Input.Color;
        }
        else
        {
           color = Input.Color * tex2D(s, Input.TexCoord.xy);
        }
     float a = color.a;
      p += 1.0;
      p /= 2;
      p.y = 1.0 - p.y;

      float3 lightAttenuation = float3(0.05,4.0, 0.0);
     // float4 color = Input.Color * tex2D(s, Input.TexCoord.xy);
      float2 aux = float2(x,y) - p.xy;
      float dist = length(aux);
      float attenuation=1.0/(lightAttenuation.x+lightAttenuation.y*dist+lightAttenuation.z*dist*dist);

      float3 lightAttenuation2 = float3(0.0,2.1, 1.0);
      float2 aux2 = float2(-1.5 + x,0.4 + y) - p.xy;
      float dist2 = length(aux2);
      float attenuation2=1.0/(lightAttenuation2.x+lightAttenuation2.y*dist2+lightAttenuation2.z*dist2*dist2);

      float4 c = (float4(attenuation,attenuation,attenuation,1.0) * color * float4(1.0,0.9,0.9,1.0) * 0.2) + (float4(attenuation2,attenuation2,attenuation2,1.0) * color * float4(1.0,0.8,1.0,1.0) * 0.2);

      color = c;

      color.a = a;

      return color;
   }

```

# Answer
> 2 votes
You're right, pixel shaders don't let you read from the destination pixel in the render target. That's what the alpha blending stage is for: combining the pixel shader output color with the current color in the destination render target.

The blend stage is configured by the application, not the shader code. It's not clear from your question which version of D3D you're using, but here's an overview of how to set up the blend stage in D3D11; other APIs are conceptually similar. The fields of the D3D11\_RENDER\_TARGET\_BLEND\_DESC1 structure let you specify how to combine the PS output color/alpha ("source") and the destination color/alpha ("dest") into the final color that gets written to the render target. One common setting is:

* SrcBlend = D3D11\_BLEND\_SRC\_ALPHA
* DstBlend = D3D11\_BLEND\_INV\_SRC\_ALPHA
* BlendOp = D3D11\_BLEND\_OP\_ADD

This uses the PS output alpha to blend directly between the render target color and the PS output color. If the output alpha is zero, the render target color is unchanged, and if the alpha is one, the render target color is totally replaced by the pixel shader output. Intermediate values blend smoothly between the two.

If you'd rather have strictly additive blending (where the pixel shader can only brighten the render target -- often used when rendering light quads, as you seem to be doing), then try:

* SrcBlend = D3D11\_BLEND\_SRC\_ALPHA
* DstBlend = D3D11\_BLEND\_ONE
* BlendOp = D3D11\_BLEND\_OP\_ADD

Many different effects are possible; check the docs for more details.

---
Tags: c++, shaders, hlsl
---


title: Island Generation Library

text:
# Question
Title: Island Generation Library
Can anyone recommend a tile map generator (written in Java is a plus), where one can control some land types? For example: islands, large continents, singe large continent, archipelago, etc.

I've been reading through many posts on the subject, it almost seems like many are just rolling their own. Before creating my own, I'm wondering if there's already an open source implementation that I might not be finding.

If not, it seems like using Perlin Noise is a popular choice.

Some articles I've been reading:

http://simblob.blogspot.com/2010/01/simple-map-generation.html

Generate islands/continents with simplex noise

https://sites.google.com/site/minecraftlandgenerator/

# Answer
Notch made the source for Minicraft open for everyone. it uses a Diamond Square algorithm that i nicked for a C# version (almost a copy paste) maybe worth checking that out.

I have never used java before and i was up and running with it within minutes
> 1 votes

---
Tags: java, maps, procedural-generation, open-source, heightmap
---


# Question
Title: How can I scale player/enemy stats to balance the difficulty just right?
I'm creating an old school top-down grid based RPG, where you enter random encounters every few steps. I want to know what kind of systems or guidelines there are for creating the leveling and stats system for such a game. Right now I'm just sort of guessing based on intuition and it's clear that that isn't going to work for very long.

For example, let's say I have a max level cap of 50, and 10 dungeons. The ideal would be that the player should need to gain about 5 levels per dungeon in order to stand a chance in the next dungeon, but that the monsters in the current dungeon can't provide enough XP to skip the next dungeon (within a reasonable amount of time anyway).

The easy route that I can think of would be to just define every enemy as worth 1 XP, and then set the amount of XP required for the next level in increasing increments, so that I only really have to track number of kills (level 1 --\> 2 would be 10 XP, or 10 kills, level 2 --\> 3 would be 12 XP, or 12 kills, etc.). But that's boring. As a player myself, I like to see the numbers related to my actions get larger over time (i.e. at level 1 --\> 2 as 10 XP, but level 2 --\> 3 as 150 XP, etc.).

And that's not even counting for stats like Strength, Vitality, and so on. But that in itself is a whole other question: are there any kinds of formulas for stats and their effects on each other? For example, enemy has 50 armor, and my guy has 30 strength. That is considerably more armor than strength, so I would expect my hit to be pretty weak...but how can I calculate those statistics to get a final damage number?

Are there any guides or any kind of "standards" for such basic systems? Even if "every game is different," I still need to learn the absolute BASIC ideas for "most" games. I have questions such as, "if you have an agility-like stat, what is a common way to determine dodge rate?" and so on.

EDIT: I found this after posting, but I'm gonna include the link here if someone else stumbles across this with similar questions. Balancing Player vs. Monsters: Level-Up Curves

# Answer
> 11 votes
You are asking ten questions at once, and some of these require whole books to answer. Still, let me try to give you some pointers before the question is closed by a moderator:

Try these websites to learn some basics about balancing. Follow the links and book recommendations if you want to learn more:

**Balance and pacing:**

**Battle mechanics:**

My advise is to NOT copy the mechanics of other games, especially if they're as crude as your "agility, armor, strength" characterization suggests. Read the whole http://gamedesignconcepts.wordpress.com series and use the techniques described there to design and test your own system.

---
Tags: game-design, rpg, balance, statistics
---


title: Are game manuals worthwhile anymore?

text:
# Question
Title: Are game manuals worthwhile anymore?
Is there any point in including manuals with games today? It seems like most manuals are more for background story or art than any actual help. Additionally, it seems like most games are including "help" inside of their games in the means of tutorials or similar means. Do enough users actually look at their manuals to make them worthwhile to include?

# Answer
> 18 votes
You could just as easily ask the broader question: should ANY software include a manual?

Amusingly, there's an article on JoelOnSoftware about designing software so that the users don't need the manual: http://www.joelonsoftware.com/uibook/chapters/fog0000000062.html

While it doesn't answer the question, it hints at it: "Users do just-in-time manual reading, on a strictly need-to-know basis."

I would say that is one reason why the game manual is important. It's a physical, tangible object that can be used as reference if the player gets stuck or forgets how certain commands work. (Yes, you can and should include this information within your in-game help system as well, but players don't always like to use that. For one, they might not be able to find it, in which case the physical manual is a suitable backup. For another, a lot of help systems require going through loading screens which seem slow to some players, so it feels faster to look it up in the printed manual.)

The other reason is that some players DO prefer to read the manual before playing. Yes, you can include an online document on the disc, but it's easier to read a printout than a computer screen. For the sake of saving a couple bucks, are you going to take some nontrivial portion of your players and make sure their **first experience** with your game is frustration at not having a manual?

There are other psychological reasons. A manual adds perceived value; you didn't just buy this disk with data on it, you also got this pretty book **absolutely free**! More to the point, manuals are so ubiquitous in games that if there isn't a manual in there, the player might assume this was a manufacturing error, and you can expect to be taking a lot of tech support calls (and handling a lot of returns) when players assume something was supposed to be there and was missing.

# Answer
> 5 votes
Manuals, like loading screens, are a great place to show off concept art and backstory that couldn't be fit into the game for whatever reason. If you're making a match-three game, you probably don't need a manual (or loading screens). If you're making a flight sim, or a train sim, or SimLife (which came with not just a manual but a lab notebook), you'd better have some reference I can use at the same time as playing the game.

If you're distributing on console platforms, the TCRs may demand a manual. Some games, like No More Heroes (Japanese Wii) or Contact (North America DS) use this opportunity to make some extremely clever designs.

# Answer
> 4 votes
Starcraft 2 comes with a "Quickstart Guide".

* 4 pages of troubleshooting
* 9 pages of backstory fiction
* 6 pages of EULA
* 7 pages of art
* One *paragraph* of installation instructions, which is basically "put it in your drive and doubleclick it"

There is not a single word about gameplay.

I honestly feel like if Blizzard isn't bothering, you probably shouldn't bother either, unless you've got a game that is actually more complicated than Starcraft 2. Like a flight sim, and basically nothing else.

# Answer
> 3 votes
For a F-15 flying simulator. Yes.

For anything else I'm not sure, probably can get away with it but a small handbook probably wouldn't hurt. Specially if it includes how the basic game mechanics work in many languages.

# Answer
> 3 votes
Well, i for one enjoy reading a manual, often there are some tips included which you do not see in the game directly.

But setting that aside, I am convinced that games should be designed in such a manner that manuals are not neccessary in order to play the game ( so if we look at the pure use of a manual considering it's original purpose, no it is not worthwhile).

Now, for the huge but; As I already mentioned there are people who simply enjoy a well written and illustrated manual, not just backstory. But stuff you can read on. For example, if I order some version of a game titled with "Game XX Gold/Deluxe/Whatever" I at least simply expect a nice manual in there. It's like with the game boxes, etc.

So, yes, if we look at it from this perspective, manuals are worth to be included ( also they usually are not pirated or anything, so you give your audience another reason to actually buy your game).

# Answer
> 3 votes
I really like a good manual. Something I can look at when my computer is turned off. Garden, loo, whatever..

A manual can contain background stories, images, concept art, etc.

A good printed manual adds good value to a game.

Doesn't have to be a huge manual, though - Civilization II anyone?

A small, well designed one will do.

# Answer
> 2 votes
In general you want the game to teach players how to play through a fictionally integrated tutorial. Few players ever bother to even look at the manual, much less read it before diving into the game.

# Answer
> 2 votes
For both of the games we have released in my time here, the manual was out of date before it even hit the printer. With an online game you are tweaking until about an hour before release, so almost anything you write about UI or controls will probably be wrong (remember that manuals have to be ready about 3-4 months before launch). Having a guide on your website is downright required though.

# Answer
> 2 votes
It depends on your game. If it is rather simple to comprehend or includes a well-done tutorial, a manual is not needed. For complicated games where the player might want to pause and have a look at a rather lengthy explanation, it shouldn't have to be read from screen and therefore be in a printed manual.

Ideally IMHO, a game is designed in a way such that a manual is not required, but still provided with one including some additional contents like background stories etc. to reward those who still RTFM (read the *friendly* manual). For example, Homeworld could be played without reading the manual thanks to a good tutorial, but reading it would provide additional background on what pre-dates the game story.

# Answer
> 2 votes
I just found this game that is "manual-ware." It's an interesting model...

The game is free, but you can support it by buying a manual:

> The 12-page, full-color printed manual for Sanctuary 17 includes basic information on playing the game, a rundown of all the enemies and items you’ll encounter, helpful strategy tips, and even some behind-the-scenes secrets. If you enjoy the game, please consider buying a copy! Your contributions will help support future games and will most likely result in a warm and fuzzy feeling from supporting indie gaming as a whole. Plus, in these days of downloadable content and PDF manuals, who can resist the allure of an actual, physical, bound bundle of papers you can leaf through at your leisure? This is a win-win situation here.

# Answer
> 1 votes
While providing an in-game tutorial is necessary, I think including a manual is also a good idea even if unused for most cases. Sometimes, you'll play a game for a while and then stop playing it for a long time. When you come back to playing the game again, it is helpful to be able to refer to a manual as a quick reference on how the game worked rather than having to boot up the game and navigate through the game menus. While this would only affect the small amount of players who would use it in this way, it is still worth it to put it in as an extra touch which would make your game feel much more complete in its boxed package.

# Answer
> 1 votes
I think it's a marketing decision. Do we want to include the concept art? Do we want to jack up the price by including 50 pages of instructions and back-story. I don't know where I'd be without my Final Fantasy manuals! Sure, you don't *realy* need them but they're part of the game; part of the package that you buy.

# Answer
> 1 votes
Cases where manuals can be helpful:

1. I think it's good to have manuals especially if your game has data that is semi-vital and a whole lot of work to memorize. Examples of which are Pokemon's resistance tables and Shin Megami Tensei's fusion charts.
2. In the old days manuals were also used to hint at hidden or secret stuff (but I guess we have gamefaqs now). I.e. Dragon Spirit wrote the secret gold dragon trick on the manual, Goonies also had the inventory trick on the manual.
3. Technical stuff (like installation as other's mentioned)

# Answer
> 0 votes
The purpose of a manual is to teach the player about your game. The more ways you have to teach the player, the more likely they are to understand/absorb what you are trying to tell them.

Take the example of the school classroom.

Early teaching methods included: lectures, books, sample problems, discussion, exams.
Technology has brought new methods of teaching to the classroom: videos, web-conferencing, online resources.

Despite the presence of these new teaching methods, the older methods still work - and are still used. Different people favour different styles of learning.

If a user doesn't understand your game, they are less likely to play it. So, why not give them every opportunity to understand it?

---
Tags: manuals
---


title: Distrubuted Rendering in a CAVE system

text:
# Question
Title: Distrubuted Rendering in a CAVE system
I am currently working with CAVE systems and I'm looking into hooking up a pre-exisiting game engine in one. I know this is possible through Unity and the Unreal Engine as there is already research out there showcasing that it has been done.

Right now, I have not decided upon one game engine to use and I'm currently looking around and researching if it is possible with the likes of CryEngine and Valve's Source Engine. The one issue that I am going to face, however, is getting the image to correctly render across all four of the monitors / screens.

Thusly, as a result I have two questions:

1. Does anyone know of any good research / books on distrubuted rendering? It doesn't need to be specificly for games, just the topic in general would be very useful
2. Does anyone know if other developers have managed to get Source and the CryEngine to run in a CAVE system? Through all my research I haven't been able to find anything on this, but then my google skills aren't the greatest.

If anyone could spare the time to answer these questions, I'd be extremely greatful.

Thanks.

# Answer
> 2 votes
This isn't a research article on the subject (for that I would refer you to the Electronic Visualization Lab at the University of Illinois in Chicago where CAVE was invented) but having worked with these sorts of systems in the past I can say that CAVE style rendering almost always depends on having multiple cameras pointing in different directions all located at the same place.

There may be more exotic approaches out there (involving some sort distorted camera FOV or something) but every time I've done it was with multiple cameras parented to the viewer, and each camera carefully setup so that the multiple views line up appropriately. In a traditional CAVE setting the cameras are pointed at 90 degree angles from each other, but I've done things like a super-wide view by making the cameras side-by-side:

http://vimeo.com/8629035

http://www.newarteest.com/coa/coa.html

Then you feed out each camera's view to a separate video card, with each projector in the CAVE hooked up to a different video card.

---

Incidentally, I wasn't using any of the engines you mentioned, but any 3D graphics engine that supports multiple cameras (which almost certainly includes all the game engines you mentioned) should do. Because CAVEs generally exist within academic settings, the graphics engines usually used also come from academic settings, like Ygdrasil or Electro

---
Tags: rendering
---


# Question
Title: Technique for objects following each other in complete movement?
I'm wondering how objects follow each other where they move over the previous position of the object in front of them. When the leading object stops, all that are following should stop at their position. So how is this achieved?

Like so:

Edit:
What I want to achieve is that all the following objects "walk" the path the leading object in front is taking. All the other objects just move at the speed of the leading object ( this would be by passing the velocity vector to all the following objects). But how do I let all the objects move/pause over the path while maintaining their distance from each other as well.

# Answer
> 11 votes
Use a List called "Path" to store the way-points that describe your path, and a doubly-linked list called "Snake" to store the moving objects and Path.

The leading object defines new way-points as it travels. The following objects move along the path as defined by these way-points.

Each object has a security zone defined by some distance. If the leading object stops, the following objects move on only until they would touch the security zone of their predecessor.

Here's some pseudo-code for how these things could be implemented. Be aware that this might not be the most elegant solution in terms of distribution of responsibilities and encapsulation.

```
class Position {
    property x;
    property y;
}
class WayPoint extends ListNode {
    property position;
}
class Path extends List {
    property WayPoints = array();

    // Find out the x, y coordinates given the distance traveled on the path
    function getPositionFromDistanceFromEnd(distance) {
        currentWayPoint = this->first();
        while(distance > 0) {
            distanceBetweenWayPoints = this->getDistance(currentWayPoint, currentWayPoint->next());
            if(distanceBetweenWayPoints > distance) {
                position = ... // travel remaining distance between currentWayPoint and currentWayPoint->next();
                return position;
            } else {
                distance -= distanceBetweenWayPoints;
                currentWayPoint = currentWayPoint->next();
            }
        }
    }
    function addWayPoint(position) {
        // Vector describing the current and new direction of movement
        currentDirection = this->first() - this->second();
        newDirection = position - this->first();
        // If the direction has not changed, there is no need to add a new WayPoint
        if( this->sameDirection(currentDirection, newDirection) {
            this->first->setPosition(position);
        } else {
            this->add(position);
        }
    }
}
class Snake extends DoublyLinkedList {
    property Path;
    property MovingObjects = array();
}
abstract class MovingObject extends DoublyLinkedListNode {
    property Snake; // shared among all moving objects of the same snake
    property position;
    const securityDistance = 10;
    abstract function move() { }
}
class MovingObjectLeader extends MovingObject {
    property direction;
    function move() {
        this->position += this->direction * this->Snake->speed;
        this->Snake->Path->addWayPoint(this->position);
        if(this->hasFollower()) {
            this->follower->move();
        }
    }
}
class MovingObjectFollower extends MovingObject {
    property distanceFromEnd;
    function move() {
        this->distanceFromEnd += this->Snake->speed;

        // If too close to leader: stop in order to respect security distance
        if(this->distanceFromEnd > this->leader()->distanceFromEnd - this->securityDistance) {
            this->distanceFromEnd = this->leader()->distanceFromEnd - this->securityDistance;
        }

        this->position = this->Snake->getPositionFromDistanceFromEnd(this->distanceFromEnd);

        if(this->hasFollower()) {
            this->follower->move();
        }
    }
}

```

Path-\>WayPoints becomes bigger and bigger the longer the game goes on. If your Snake exists for quite some time, you need to delete the last WayPoint whenever the last element of the Snake has passed the second-to-last WayPoint of Path. Remember to also reduce distanceFromEnd in all MovingObjects of Snake accordingly.

# Answer
> 6 votes
Essentially you'll need two data structures (logical, intrusive, or real, depending on the rest of your code). The first will track the chains of objects, and the other the path.

**Chain** Simply you need to know which objects are following other objects. In the simplest case this will simply be A follows B, but could include more followers. There is a designated *leader* in the chain.

**Path** For each chain you'll need a path. Depending on how your game works will determine how this is structured. In most cases it will be some kind of linked list. This will track the positions that everybody in the chain needs to follow.

Now, the *leader* in the chain will be adding items to the *path*. Each time it moves it will add something to the head of the list. Each object in the chain remembers where on the list it is. When it comes to moving it simply moves to the next item in the list (interpolated appropriately if necessary). As the last item in the chain moves past an item in the list, that item can be dropped (it will be at the tail).

Metaphorically the leader leaves a breadcrumb trail for its followers. The last follower in the list consumes the breadcrumb.

Whether your list contains individual points, or just the vertices of a path, or something else, is determined entirely by your game engine. But in any case I don't see that you'll be able to avoid the list itself.

# Answer
> -3 votes
Lookup A\* pathfinding. This is a general & easy way to have your game entities / objects go to/follow a position.

---
Tags: movement
---


title: Math and physics, where to start?

text:
# Question
Title: Math and physics, where to start?
the only math I know how is to add the velocity to position. Thats it. i would like to know how to do more stuff, physics, collision detection with stuff other than perfect circles, etc. But where ever I go online to find source to learn I always end up with something that assumes prior knowledge, which is understandable in a lot of cases. But I don't know where to go to learn math and physics from the absolute beginnings. Also I'm dyslexic, so sites or ressources with just definitions of concepts and no relatable examples wont help that much. So could someone give me some links to books and/or sites that can help me learn math and physics for game development.

# Answer
> 5 votes
I would typically say this question is off topic, since where to get started is different for everyone. But I think Khan academy is a resource that accommodates a wide range of skill levels. It'll teach you physics and any math you need to get into physics. You can start at whatever level you're comfortable with from basic addition to calculus. The videos are well done, easy to follow and enjoyable to watch.

# Answer
> 4 votes
There's some good resources for learning Maths here on the BBC site, has a range of level such as GCSE (secondary), A-Level (high school?) and university level.

BBC maths resources

# Answer
> 3 votes
One option is to watch some MIT lectures. You can start at the smallest course numbers and work your way up for the first few classes in the physics and math departments.

# Answer
> 3 votes
This year I've been trying to learn more maths for use in making game and the method that has been working for me is to first watch as much Khan Academy as your brain will allow, especially around the area of linear algebra. Then grab this book: Essential Mathematics for Games and Interactive Applications: A Programmer's Guide

And again do as much as your brain will allow, I spent a weekend solid working on the book and followed it up with a few hours here and there in coffee shops but then my brain was full.

As soon as it is full, make some games. They don't have to be complicated, or even work well enough to give to ANYONE but just start coding something and you will soon have some moments where you go. "Hmmm... I could use dot product here" or "Why aren't I doing this with a matrix?" and at that point you have won!

Honestly games (for a hobby at least) should be fun for the person making them as well as for the person who will play it. Don't worry too much if you get stuck on the maths for a time (I haven't picked the book up in a month now but I have been coding loads and using what I have read). You will find that after a while you are running into situations you don't know how to handle more frequently again and you'll naturally drift back to the book and study some more. I've been finding this style very low pressure and very rewarding.

As for the dyslexia, that makes things a little trickier. I have obviously suggested the book that has worked for me but in an environment where books cost so much I'd suggest getting a selection of them through more nefarious means, finding which one suit your learning style, buying that one and deleting the rest. I know its not great to steal books, even temporarily, but no library will stock a decent selection of these kind of books and it really sucks to hand over lots of cash for a book that you find you can't learn from.

Wow that was much longer than I thought it would be, best of luck on your hunt!

---
Tags: mathematics, physics
---


title: Change alpha to a Frame in libgdx

text:
# Question
Title: Change alpha to a Frame in libgdx
I have this

```
batch.draw(currentFrame, x, y, this.parent.originX, this.parent.originY, this.parent.width, this.parent.height, this.scaleX, this.scaleY,this.rotation);

```

I want to apply the alpha that it gets from the method, but theres is not overload from the SpriteBatch class that takes the alpha value, is there some wey to apply it? (i did it this way, because this are animation, and i wanted to control them) in my static ones i apply

```
sprite.draw(SpriteBatch, alpha)

```

Thanks

# Answer
There isn't a built-in way of doing this, but you can do it by temporarily modifying the Color which SpriteBatch blends your texture with; usually used for tinting though. This is untested, but it should work...Let me know if it does.

```
Color color = batch.getColor();//get current Color, you can't modify directly
float oldAlpha = color.a; //save its alpha

//From here you can modify alpha however you want
float scale = 0.5;
color.a = oldAlpha*scale; //ex. scale = 0.5 will make alpha halved
batch.setColor(color); //set it
batch.draw(currentFrame, x, y, this.parent.originX, this.parent.originY, this.parent.width, this.parent.height, this.scaleX, this.scaleY,this.rotation);

//Set it back to orginial alpha when you're done with your alpha manipulation
color.a = oldAlpha;
batch.setColor(color);

```

This is actually similar to what `sprite.draw(SpriteBatch, alpha)` do if you look at source.
> 7 votes

# Answer
Another way could be to use Sprites instead of TextureRegion for the Animation (you have to cast the TextureRegion probably) since Sprite has color field which uses when using it with the SpriteBatch. However, if you change to use Sprites you need to know you have to call sprite.render(spriteBatch) and no the inverse way.

Btw, if the previous answer by XiaoChuan Yu was useful remember to mark your question as answered so it is removed from unanswered questions.
> 2 votes

---
Tags: animation, libgdx
---


title: Sprite detect background color

text:
# Question
Title: Sprite detect background color
I have read somewhere that sprites can detect the background color, but I don't remember where and how it's working. What I'm trying to do is just a function to detect if the sprite is on a special surface, that has a special color, instead of using collision dedection between objects. Help is preciated! Thanks!

# Answer
> 1 votes
You can render your entire scene to a render target instead of directly to screen. A render target is also a texture and you can query the color of each pixel by getting the data from the texture. See this StackOverflow answer on how to get the color of a pixel in a texture.

Notes:

* The color data is a 1 dimensional array so you need to do a tiny bit of math to go from 2D to 1D to get the correct pixel data.
* Getting the color data like this can be slow, but don't worry about it until you experience actual performance issues. If you only do this once per frame you should be alright.

Other resources:

You can find a tutorial for XNA here that uses a texture as a color key for collision detection. A lot of the techniques you need are explained there in detail so be sure to check it out!

---
Tags: xna
---


title: Triangle Strips of Tetraheron

text:
# Question
Title: Triangle Strips of Tetraheron
I am confused about the triangle strip representation of closed mesh .The vertex buffer for triangle strip representation of the a figure is shown below:

A(0,1) B(0,0) C(1,1) D(1,0)E(2,1)

vertex buffer=\[A,B,C,D,E\] where, T1=(A,B,C) T2=(B,C,D) T3=(C,D,E)

Now, if I have a tetrahedron with four vertex A(0,0,0),B(1,0,0),C(0,1,0) and D(0,0,1) then what would be its vertex buffer representation?

Thank you very much.

# Answer
> 3 votes
short answer:\[A,B,C,D,A,B\]

you'll need 4 triangles to create a Tetrahedron. so you'll need 6 vertices in your buffer. not that for the first three vertices you'll only get one triangle but for every other vertex you'll have one extra triangle. now back to your problem, as I said you'll need 4 triangles represented as \[A,B,C\], \[A,B,D\], \[A,C,D\] and \[B,C,D\] with a little bit sorting you can easily arrange them into a form that each two consecutive triangle share two vertices \[A,B,C\], \[B,C,D\], \[C,D,A\] and finally \[D,A,B\]. then by combining all those together you'll have your full vertices arrangement which is exactly as I mentioned above.

---
Tags: rendering, 3d-meshes, vertex-arrays
---


# Question
Title: Ranking system in an Android Open Source project
This is my first question in any stackexchange board, but I've been reading Stack Overflow answers for a few months. I hope this question is appropriate for this one.

I am developing a simple Android game using Java and libgdx. I want to make a typical ranking, a player who completes a level is awarded some points, and his score is compared with other players who sent theirs. This is all ok (well I still need to find a way to store players' scores). On the other hand, I may want my project to be released as an open source project, so others can look at its code freely. My question is, if anybody can get this code, modify it in order to get some advantatge, compile this game, and load it onto an Android device, how can I stop him/her from sending his/her score? It would by unfair to let them send highscores with a different game.

# Answer
You could release the whole game with the exception of a file that stores the private key of your game. When something sends a score, you send back a random string that is encrypted with the game's public key. You only accept the score if the program sends back the original message. This should work as long as the file with the private key cannot be extracted from the compiled version of your game.
> 1 votes

# Answer
From my perspective, you should share your entire source code so anyone could make his own version of the game and run his ranking server instance.

Cheating is not the only thing that may worry you, for example imagine that someone starts making huge petitions to your server and you will pay that expenses.

What I recommend is that you release the entire source code and let anyone mount it´s own server instance for the rankings. As BerndBrot says, do not share your dbconnect or whatever file with the credentials to modify the rankings.

Kind regards.
> 0 votes

---
Tags: android, open-source, ranking
---